我正在尝试使用Fluent API(EF6)将实体映射到现有数据库。每当我尝试运行应用程序时,都会收到以下错误:
One or more validation errors were detected during model generation:
FooId: Name: Each property name in a type must be unique. Property name 'FooId' is already defined.
FooId: Name: Each property name in a type must be unique. Property name 'FooId' is already defined.
BarId: Name: Each property name in a type must be unique. Property name 'BarId' is already defined.
以下是数据库中有问题区域的简化视图。所以我们有一个Bar实体,它与一个或多个Foo实例相关。每个Foo可能与一个MoreFoo相关,每个MoreFoo可能与多个EvenMoreFoo实例相关。
请注意,EvenMoreFoo实体具有复合主键!另请注意,为了将MoreFoo链接到Foo,等价的MoreFoo.FooId = Foo.FooId必须为true。将EvenMoreFoo链接到MoreFoo也是如此。
使用Fluent API的关系映射如下所示:
modelBuilder.Entity<Foo>()
.HasOptional(x => x.Bar)
.WithMany(x => x.Foos)
.HasForeignKey(x => x.BarId);
modelBuilder.Entity<MoreFoo>()
.HasRequired(x => x.Foo)
.WithOptional(x => x.MoreFoo)
.Map(x => x.MapKey("FooId"));
modelBuilder.Entity<MoreFoo>()
.HasMany(x => x.EvenMoreFoos)
.WithRequired(x => x.MoreFoo)
.HasForeignKey(x => x.FooId);
modelBuilder.Entity<EvenMoreFoo>()
.HasRequired(x => x.MoreFoo)
.WithMany(x => x.EvenMoreFoos)
.HasForeignKey(x => x.FooId);
我不知道为什么会抛出错误。没有实体具有两次定义的相同属性名称,因此它与使用Fluent API映射关系的方式有关。是否在多个实体上使用了密钥FooId?如果有人能告诉我我犯的错误,我会感激不尽。
经过一些更多的玩弄后,我得出结论,错误在以下映射中(更具体:它的最后一行):
modelBuilder.Entity<MoreFoo>()
.HasRequired(x => x.Foo)
.WithOptional(x => x.MoreFoo)
.Map(x => x.MapKey("FooId"));
在整个代码库中,这样做了三次:FooId
两次,BarId
一次。这与错误相对应。仍然试图弄清楚如何修复它。
答案 0 :(得分:1)
对于此代码段,它执行正常:
public class Foo {
public int FoodId { get; set; }
public ICollection<MoreFoo> MoreFoo { get; set; }
public int BarId { get; set; }
}
public class MoreFoo {
public int FooId { get; set; }
public Foo Foo { get; set; }
public string SomeAttr { get; set; }
}
var modelBuilder = new DbModelBuilder();
modelBuilder.Entity<MoreFoo>()
.HasRequired(x => x.Foo)
.WithMany(x => x.MoreFoo)
.HasForeignKey(x => x.FooId);