【问题标题】:Junction Table in ASP .NET code first approachASP .NET 代码优先方法中的连接表
【发布时间】:2017-02-28 21:02:32
【问题描述】:

我正在创建身份用户和游戏表之间的联结表。此表称为 UserGame,具有两个外键(UserID、GameID)和一个用于存储分数的附加字段。

public class UserGame
{
    [Key]
    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public int GameID { get; set; }
    public virtual Game Game { get; set; }

    public int Score { get; set; }
}

我的困惑在于创建新的 UserGame 记录。我将如何去做,我的方法是否正确?

更新(有效):

 [HttpPost]
    public ActionResult SubmitScore(int gameID, int score)
    {
        var playerRecord = new UserGame();

        playerRecord.ApplicationUserID = User.Identity.GetUserId();
        playerRecord.GameID = gameID;
        playerRecord.Score = score;

        return Json(new { success = true });
    }

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework asp.net-identity junction-table


    【解决方案1】:

    ApplicationUserIdGameId 都必须具有 [Key, Column(Order = 0)] 属性。只需将第一个设置为 Order 0,另一个设置为 1。

    public class UserGame
    {
        [Key, Column(Order = 0)]
        public string ApplicationUserID { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    
        [Key, Colum(Order = 1)]
        public int GameID { get; set; }
        public virtual Game Game { get; set; }
    
        public int Score { get; set; }
    }
    

    然后您可以选择添加新记录,通过GameApplicationUser 的导航属性或直接使用您的UserGame 类。

    【讨论】:

    • 感谢您的帮助!添加新记录时仍然有些失落。我选择直接使用我的 UserGame 课程。我在控制器中创建了一个新的 UserGame 对象。我可以分配游戏 ID 和分数。我想知道这种方法是否正确:检索通过 User.Identity.GetUserID() 登录的当前用户并将其设置为 ApplicationuserID 字段。
    • 是的,这是一种方法,添加新的 UserGame 实体,将其添加到您的上下文中。你应该在你的 DbContext 中将它作为 DbSet 吗?
    • 它现在正在工作,在任何地方都找不到这种方法。非常感谢
    【解决方案2】:

    Example of configuring many-to-many relationship in entity framework

    Examle of inserting related objects

    几个提示: 我不会在联结实体中声明主键,因为联结通常由复合键定义。 请记住,dbcontext.SaveChanges() 将查找子实体并保存它们。

    【讨论】:

    • 感谢您的回答,我对该示例的问题是存储附加字段“分数”。这应该在 Game 类中吗?
    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    相关资源
    最近更新 更多