是否可以与使用链接/联接表的 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 重用。
Entity Framework 可以做到这一点吗?我宁愿不必将键放在 Foo 本身中,因为我不想要一个可为空的外键。如果可能,请提供使用 Fluent API 而不是数据注释的示例。
最佳答案
您可以使用实体拆分来实现此目的
public class Foo
{
public int FooId { get; set; }
public string Name { get; set; }
public int BarId { get; set; }
public virtual Bar Bar { get; set; }
}
然后在您的自定义 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");
}
BarId
列将在 FooBar
中创建为非空列 table 。您可以查看 Code First in the ADO.NET Entity Framework 4.1更多细节
关于c# - Entity Framework 代码优先 - 具有连接/链接表的一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7517675/