0
我想存储一些对象,每个Foo只有一个Bar。如何在实体框架中创建1:1关系?
我有一个看起来像这样一些POCO对象:
public class Foo
{
public int Id { get; set; }
public string FooProperty { get; set; }
public int BarId { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string BarProperty { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
的Foo和酒吧有一个1:1的关系,并根据读我已经做了我想在我的DbContext类以下:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<Foo>()
.HasRequired(x => x.Bar)
.WithRequiredPrincipal(x => x.Foo);
base.OnModelCreating(modelBuilder);
}
后备存储是SQL Server,这确实为我创建了具有1:1关系的表。 然而,从Bar
到Foo
的FK关系是两个表的Id
领域,而我希望它是从Bar
表的FooId
领域的Foo
表的Id
领域。
EF似乎已决定保持两个表的PK(Id)字段同步,并且基本上忽略了我的列(BarId
/FooId
)。
我在做什么错?
感谢。我确实需要1:1,并且我想共享PK是可以的。我将FooId/Foo和BarId/Bar属性添加到我的POCO对象的原因是因为根据我读过的“如何”文章推荐这样做。它在1:很多情况下都有效,而且看起来有些奇怪,因为它们是1:1而不具备这些参数。我认为代码优先的东西是为了在很大程度上消除后备存储和对象之间的耦合... – 2012-08-06 16:30:26