如何使用实体框架代码优先自定义外键列名称
我有以下模型
public class Foo
{
public int Id { get; set; }
public IList<Bar> Bars { get; set; }
}
public class Bar
{
public int Id { get; set; }
}
当我首先使用 EF 代码从中生成数据库架构时,它会创建以下表:
Foo
- Id (PK, int, not null)
Bar
- Id (PK, int, not null)
- Foo_Id (FK, int null)
是否可以使用属性更改 Foo_Id 外键的名称?
编辑:这是满足我需要的版本:
public class Foo
{
public int Id { get; set; }
[ForeignKey("AssignedToBarId")]
public IList<Bar> Bars { get; set; }
}
public class Bar
{
public int AssignedToBarId { get; set; }
public int Id { get; set; }
}
I have the following model
public class Foo
{
public int Id { get; set; }
public IList<Bar> 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<Bar> Bars { get; set; }
}
public class Bar
{
public int AssignedToBarId { get; set; }
public int Id { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为可以像下面这样完成:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity.Map(c => c.MapKey(u => u.Id, "AssignedToBarID"));
}
或者也许:
注意:我还没有测试过它们。这些只是建议。
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:
NOTE: I have not tested neither of them. These are just suggestions.