简体   繁体   中英

C# Entity Framework Foreign Key attribute ignored

I have "User" and "Product" entities, product has foreign key to user (UserId -> User). I am trying to add one more foreign key to user in product entity, but getting wrong migration

My updated product entity (example)

    [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; }

Automaticaly created migration:

        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");

So my UserId property is ignored

I think you have to many ForeignKey data annotations.

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

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

You could use fluent API like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM