实体框架代码优先 - 具有联接/链接表的一对多
是否可以使用 Code First 创建一对多关系,并在它们之间使用链接/联接表?
public class Foo {
public int FooId { get; set; }
// ...
public int? BarId { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar {
public int BarId { get; set; }
// ...
public virtual ICollection<Foo> Foos { get; set; }
}
我希望它映射如下:
TABLE Foo
FooId INT PRIMARY KEY
...
TABLE Bar
BarId INT PRIMARY KEY
TABLE FooBar
FooId INT PRIMARY KEY / FOREIGN KEY
BarId INT FOREIGN KEY
这样,我就能够确保 Foo 只有一个 Bar,但该 Bar 可以被许多不同的 Foo 重复使用。
这可以通过实体框架实现吗?我宁愿不必将密钥放在 Foo 本身中,因为我不想要可为空的外键。如果可能,请提供使用 Fluent API 而不是数据注释的示例。
Is it possible to create a One-to-Many relationship with Code First that uses a link/join table between them?
public class Foo {
public int FooId { get; set; }
// ...
public int? BarId { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar {
public int BarId { get; set; }
// ...
public virtual ICollection<Foo> Foos { get; set; }
}
I want this to map as follows:
TABLE Foo
FooId INT PRIMARY KEY
...
TABLE Bar
BarId INT PRIMARY KEY
TABLE FooBar
FooId INT PRIMARY KEY / FOREIGN KEY
BarId INT FOREIGN KEY
With this, I would have the ability to make sure Foo only has one Bar, but that Bar could be re-used by many different Foos.
Is this possible with Entity Framework? I would prefer to not have to put the key in Foo itself because I don't want a nullable foreign key. If it is possible please provide an example using the Fluent API and not the data annotations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用实体拆分来实现此目的
然后在自定义 DbContext 类中
BarId
列将被创建为FooBar
表中的非空列。您可以查看 ADO.NET Entity Framework 4.1 中的 Code First更多细节You can use Entity splitting to achieve this
Then in your custom DbContext class
The
BarId
column will be created as a not null column inFooBar
table. You can check out Code First in the ADO.NET Entity Framework 4.1 for more details