EF Code-first MVC: Should I add fields to the defa

2019-08-15 06:32发布

问题:

I am making a simple MVC application using code first entity framework. I'm trying to use the built in user registration/login. It provides me the default AccountController and ASP User tables.

My other entities are Players, Games, and Tournaments:

public class Player
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Game> Games { get; set; }
    public List<Tournament> Tournaments { get; set; }
}

public class Game
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<Player> Players { get; set; }
    public List<Tournament> Tournaments { get; set; } 
}

 public class Tournament
{
    public int Id { get; set; }
    public List<Player> Players { get; set; }
    public List<Game> Games { get; set; }

}

EF provides these tables.

Everyone who logs in is a player. I want each player to have a password and username. Should I remove my Players table and add the Player properties to the provided User class and AspNetUsers table? Or should I use a foreign-key to create a relationship between the Players table and the AspNetUsers table?

Are either or both of those options possible/preferable?

Also just a note, there will be additional properties in the Players, Games, and Tournaments classes; I was just starting with the basics.

Thank you very much for your time. Let me know if I am being unclear or if you need any additional information.

EDIT: Just found this: http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx

It shows something like both methods I described above. What is the advantage of adding a new UserInfo table vs. adding fields to the existing table?

回答1:

I would add this property to the player table:

public virtual ApplicationUser User { get; set; }

where ApplicationUser is the table that was given out of the box by Visual Studio. The ApplicationUser uses identity so when user creates a new player, have the playerController's Create action to set the user id of the user to the player id in the player table:

var userId = User.Identity.GetUserId();
Player.PlayerId = userId;


回答2:

Add properties to ApplicationUser class. Also I suggest you to rename it to Player, so code will better match domain language.