【问题标题】:Creating Composite key in ApplicationDbContext using fluent api使用流利的 api 在 ApplicationDbContext 中创建复合键
【发布时间】:2021-05-04 04:01:33
【问题描述】:

我从 NBA API 获取数据,为了将数据写入我的数据库,我需要使用复合键 PlayerID 和 GameID 创建 PlayerGame 的 DB 对象,我尝试使用两个 [key][column=] 标签来定义但是在尝试添加迁移时,我得到了错误需要使用流利的 api。所以经过一番谷歌搜索后,我想出了以下代码,现在在尝试迁移时,我收到错误消息实体类型“IdentityUserLogin”需要定义主键。如果您打算使用无密钥实体类型,请调用“HasNoKey()”。我猜它与继承自 IdentityDbContext 的 ApplicationDbCONtext 有关,但我现在真的不知道该怎么做。请帮忙!!

我有一个类玩家游戏

public class PlayerGame
{

    [Required]
    public int PlayerID { get; set; }

    [ForeignKey ("PlayerID")]
    public Player Player { get; set; }


    [Required]
    public int GameID { get; set; }

    [ForeignKey ("GameID")]
    public Game Game { get; set; }

和数据库上下文

public class ApplicationDbContext : IdentityDbContext
{

    public DbSet<Player> Player {get; set; }

    public DbSet<Game> Game { get; set; }

    public DbSet<PlayerGame> PlayerGame { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<PlayerGame>()
            .HasKey(pg => new { pg.PlayerID, pg.GameID });
    }

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    这其实很简单。将调用移至自定义逻辑下方的基本方法,它应该可以工作。

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<PlayerGame>()
            .HasKey(pg => new { pg.PlayerID, pg.GameID });
    
        base.OnModelCreating(builder); // <-- move this line to bottom
    }
    

    您应该在调用基本方法之前完成所有自定义配置。基本方法是引发该错误的原因

    【讨论】:

    • 我有一个附加到 PlayerGame 的 PlayerBet 类 我将如何通过复合键在 PlayerBet 中获取 PlayerGame 对象?
    • 如果没有完整的代码,很难给出一个全面的答案,但可能像这样context.PlayerGame.Include(pg =&gt; pg.Bet).Find(playerID, gameID })。 find 获取数据,include 意味着它将与 PlayerGame 一起加载并接受参数,以便您设置它们。或者你可以这样做context.PlayerGame.Where(pg =&gt; pg.PlayerID == playerID &amp;&amp; pg.GameID == gameID).Select(pg =&gt; pg.PlayerBet }).FirstOrDefault()。两者都有异步版本,所以尽可能使用它们
    猜你喜欢
    • 2010-12-10
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 2013-10-24
    • 2015-04-12
    相关资源
    最近更新 更多