我们有遗留数据库,我们将新对象和道具映射到旧表和列。到现在为止还挺好。我们有成功映射的多对多关系。中间表包含附加数据。当我们尝试将中间表映射到一个对象时,我们会得到映射已经定义的异常。如果我们从关系的任何一侧删除映射,我们会得到表丢失的错误(ofc,我们期望如此)。我可以使用 NHibernate 轻松做到这一点,并且我开始认为 EF 确实缺少很多功能。所以,请告诉我我错了,我们可以用 EF 做到这一点。
最好的祝福
编辑:这是一个失败的虚拟样本。
class User
{
public ICollection<User> Followers{get;set;}
}
class UserRelation
{
public User User{get;set;}
public User Follower{get;set;}
public DateTime CreatedOn{get;set;}
}
用户映射
modelBuilder
.Entity<User>()
.HasMany<User>(user => user.Followers)
.WithMany()
.Map(m =>m.MapLeftKey("user_id").MapRightKey("follower_id")
.ToTable("user_follower"));
用户关系映射
modelBuilder
.Entity<UserRelation>()
.ToTable("user_follower");
modelBuilder
.Entity<UserRelation>()
.HasOptional<User>(f => f.User)
.WithRequired().Map(m => m.MapKey("user_id"));
modelBuilder
.Entity<UserRelation>()
.HasOptional<User>(f => f.Follower)
.WithRequired().Map(m => m.MapKey("follower_id"));
modelBuilder
.Entity<UserRelation>()
.Property(entity => entity.CreatedOn)
.HasColumnName("created_on");
例外
指定的架构无效。错误:(67,6):错误 0019:已经定义了具有模式 'dbo' 和表 'user_follower' 的 EntitySet 'UserUser'。每个 EntitySet 必须引用一个唯一的模式和表。
Edit2:这是此模型的另一个示例:http: //learnentityframework.com/LearnEntityFramework/tutorials/many-to-many-relationships-in-the-entity-data-model/