[英]Entity Framework Code First - One-to-Many with a join/link table
Is it possible to create a One-to-Many relationship with Code First that uses a link/join table between them? 是否可以与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; }
}
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. 有了这个,我就有能力确保Foo只有一个Bar,但是Bar可以被许多不同的Foo重用。
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.
我宁愿不必将密钥放在Foo本身,因为我不想要一个可以为空的外键。 If it is possible please provide an example using the Fluent API and not the data annotations.
如果可能,请使用Fluent API提供示例,而不是数据注释。
You can use Entity splitting to achieve this 您可以使用实体拆分来实现此目的
public class Foo
{
public int FooId { get; set; }
public string Name { get; set; }
public int BarId { get; set; }
public virtual Bar Bar { get; set; }
}
Then in your custom DbContext class 然后在您的自定义DbContext类中
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().HasKey(f => f.FooId);
modelBuilder.Entity<Foo>()
.Map(m =>
{
m.Properties(b => new {b.Name});
m.ToTable("Foo");
})
.Map(m =>
{
m.Properties(b => new {b.BarId});
m.ToTable("FooBar");
});
modelBuilder.Entity<Foo>().HasRequired(f => f.Bar)
.WithMany(b => b.Foos)
.HasForeignKey(f => f.BarId);
modelBuilder.Entity<Bar>().HasKey(b => b.BarId);
modelBuilder.Entity<Bar>().ToTable("Bar");
}
The BarId
column will be created as a not null column in FooBar
table. BarId
列将在FooBar
表中创建为非空列。 You can check out Code First in the ADO.NET Entity Framework 4.1 for more details 您可以在ADO.NET Entity Framework 4.1中查看Code First以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.