【问题标题】:C# Entity Framework Foreign Key attribute ignoredC# Entity Framework 外键属性被忽略
【发布时间】:2019-08-05 16:59:16
【问题描述】:

我有“用户”和“产品”实体,产品具有用户的外键(用户 ID -> 用户)。我正在尝试在产品实体中向用户添加一个外键,但迁移错误

我更新的产品实体(示例)

    [ForeignKey("User")]
    public int? UserId { get; set; }
    [ForeignKey("AcceptedBy")]
    public int? AcceptedById { get; set; }       
    [ForeignKey("AcceptedById")]
    public User AcceptedBy { get; set; }
    [ForeignKey("UserId")]
    public User User { get; set; }

自动创建的迁移:

        DropForeignKey("dbo.Products", "UserId", "dbo.Users");
        AddColumn("dbo.Products", "AcceptedById", c => c.Int());
        AddColumn("dbo.Products", "User_Id", c => c.Int());
        CreateIndex("dbo.Products", "AcceptedById");
        CreateIndex("dbo.Products", "User_Id");
        AddForeignKey("dbo.Products", "AcceptedById", "dbo.Users", "Id");
        AddForeignKey("dbo.Products", "User_Id", "dbo.Users", "Id");
        DropColumn("dbo.Products", "AcceptedByUserId");

所以我的 UserId 属性被忽略了

【问题讨论】:

  • 最初的迁移是什么样子的(这里改的那个)?
  • 导航属性不需要ForeignKey属性(AcceptedByUser
  • @Mohamed Ahmed 我试过了 - 没用
  • @grek40 这是原创(没有向下功能)
  • @StasPetrov 我的意思是,这次迁移以DropForeignKey 开始,所以肯定有以前的迁移。在不了解他们的情况下,很难说出正在发生的事情的细节。您可以尝试创建一个新的数据库并创建此模型作为初始迁移 - 名称应该按预期工作。

标签: c# .net entity-framework


【解决方案1】:

我认为你有很多 ForeignKey 数据注释。

public int? UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }

public int? AcceptedById { get; set; }       
[ForeignKey("AcceptedById")] 
public User AcceptedBy { get; set; }

【讨论】:

    【解决方案2】:

    您可以使用流畅的 API,例如:

    modelBuilder.Entity<Product>()
       .HasOptional(h => h.User)
       .WithMany()
       .HasForeignKey(fk => fk.UserId);
    

    【讨论】:

      猜你喜欢
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多