我正在使用EF codeFirst来创建我的数据库。 我有2个模型博客和消息与下面的字段,我得到一个映射冲突,因为消息表有一个外键到博客表和博客表有一个外键与lastMessage张贴到消息表。
public class Blog
{
public int BlogId { get; set; }
public string Topic{ get; set; }
public virtual Message LastMessage{ get; set; }
}
public class Message
{
public int MessageId { get; set; }
public string Text { get; set; }
public virtual Blog Blog { get; set; }
}
public class BlogMap : EntityTypeConfiguration<Blog>
{
public BlogMap()
{
// Primary Key
HasKey(t => t.BlogId);
// Properties
Property(t => t.BlogId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Table & Column Mappings
ToTable("Blog");
Property(t => t.Topic).HasColumnName("Topic").HasMaxLength(100);
// Relationships
HasOptional(t => t.LastMessage)
.WithRequired(t => t.Blog)
.Map(t => t.MapKey("LastMessageId"));
}
}
public class MessageMap : EntityTypeConfiguration<Message>
{
public MessageMap()
{
// Primary Key
HasKey(t => t.MessageId);
// Properties
Property(t => t.MessageId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Table & Column Mappings
ToTable("Message");
Property(t => t.Text).HasColumnName("Text").HasMaxLength(100);
// Relationships
HasRequired(t => t.Blog)
.WithOptional()
.Map(t => t.MapKey("BlogId"));
}
}
例外:
{&#34;导航属性&#39; Blog&#39;声明在类型&#39; MyProject.DAL.Model.Message&#39;已配置有冲突的映射信息。&#34;}
答案 0 :(得分:1)
问题是您已经两次映射了Message类的“Blog”属性。在BlogMap类中,您可以在此处定义它:
HasOptional(t => t.LastMessage)
.WithRequired(t => t.Blog)
.Map(t => t.MapKey("LastMessageId"));
这告诉EF Blog属性是LastMessageId关系的“返回”端。
在MessageMap类中,您可以在此处定义它:
HasRequired(t => t.Blog)
.WithOptional()
.Map(t => t.MapKey("BlogId"));
这表示Blog属性代表BlogId关系。
我怀疑第二个是你真正想要的那个,第一个关系的WithRequired()行应该替换为.WithOptional(),如下所示:
HasOptional(t => t.LastMessage)
.WithOptional()
.Map(t => t.MapKey("LastMessageId"));
答案 1 :(得分:1)
下面是修复,我使用WithMany()删除了关系另一侧的导航属性
将BlogId和MessageId添加到消息和博客表
博客地图:
HasOptional(t => t.LastMessage).WithMany().HasForeignKey(d => d.MessageId);
// Relationships
HasOptional(t => t.LastMessage)
.WithRequired(t => t.Blog)
.Map(t => t.MapKey("LastMessageId"));
消息映射:
HasOptional(t => t.Blog).WithMany().HasForeignKey(d => d.BlogId);
// Relationships
HasRequired(t => t.Blog)
.WithOptional()
.Map(t => t.MapKey("BlogId"));