2

我正在尝试制作一个使用内置 MVC 用户配置文件作为身份验证方法的基本网站。我正在使用 MVC4.0 和实体框架。

我有一个使用 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; }
}

我的新用户上下文是:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Game> 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();

我真的不知道我做错了什么,任何帮助将不胜感激!

4

1 回答 1

1

像这样改变你的UserProfile班级:

[Table("UserProfile")]
public class UserProfile
{
    public UserProfile()
    {
        this.Games = new HashSet<Game>();            
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int Balance { get; set; }

    public virtual ICollection<Game> 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();

请注意,您没有WagerGame模型中声明任何属性。我不知道它是什么...

于 2013-07-23T11:33:40.373 回答