How to customize foreign key column name using Entity Framework Code-first

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have the following model

public class Foo {     public int Id { get; set; }     public IList Bars { get; set; } }  public class Bar {     public int Id { get; set; } }

When I generate the database schema from this using EF Code first it creates the following tables:

Foo

  • Id (PK, int, not null)

Bar

  • Id (PK, int, not null)
  • Foo_Id (FK, int null)

Is it possible to change the name of the Foo_Id foreign key using attributes?

EDIT: Here is the version that does what I need:

public class Foo {     public int Id { get; set; }      [ForeignKey("AssignedToBarId")]     public IList Bars { get; set; } }  public class Bar {     public int AssignedToBarId { get; set; }     public int Id { get; set; } }

回答1:

I think it can be done like below:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity.Map(c => c.MapKey(u => u.Id, "AssignedToBarID")); }

Or maybe:

[ForeignKey("AssignedToBarID")] public IList Bars { get; set; }

NOTE: I have not tested neither of them. These are just suggestions.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!