在类中使用UserProfile外键在MVC 4中创建新的配置文件

我正在尝试创建一个使用内置MVC用户配置文件作为身份validation方法的基本网站。 我正在使用MVC4.0和Entity Framework。

我有一个主数据类,它使用UserProfile模型作为外键。 该类是“游戏”类,用于将游戏与特定用户相关联。

我还在UserProfile类中添加了另一个成员,作为此项目的必需品。

每当我尝试添加一个新游戏时,其中有一个用户的配置文件作为外键,服务器最终会完全创建一个新的用户配置文件,即使我专门制作它以便它是同一个用户。

作为尝试解决此问题的一部分,我将Game对象添加到用户配置文件DbContext,但这根本没有帮助,而且每次我将新游戏插入数据库时​​我仍然会创建新用户。

我的模型如下:

public class Game { public int ID { get; set; } [ForeignKey("UserId")] public virtual UserProfile Profile { get; set; } public int UserId { get; set; } } [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public int Balance { get; set; } } 

我的新UsersContext是:

 public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } public DbSet UserProfiles { get; set; } public DbSet GamesList { get; set; } } 

我添加新游戏的方法是:

  Models.UsersContext uc = new UsersContext(); UserProfile prof = uc.UserProfiles.Where(c=>c.UserName == HttpContext.User.Identity.Name).First(); Game g = new Game(); g.Profile = prof; g.Wager = int.Parse(BetQuantity); uc.GamesList.Add(g); uc.SaveChanges(); 

我真的不知道我做错了什么,任何帮助都会非常感激!

像这样更改您的UserProfile类:

 [Table("UserProfile")] public class UserProfile { public UserProfile() { this.Games = new HashSet(); } [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public int Balance { get; set; } public virtual ICollection Games { get; set; } } 

然后插入你的游戏:

 Models.UsersContext uc = new UsersContext(); Game g = new Game(); g.UserId = WebSecurity.CurrentUserId; g.Wager = int.Parse(BetQuantity); uc.GamesList.Add(g); uc.SaveChanges(); 

请注意,您尚未在Game模型中为Wager声明任何属性。 我不知道它是什么……