2014-09-12 118 views
2

我正在使用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")); 
     } 
    } 

例外:

{ 「導航屬性 '博客' 上型 'MyProject.DAL.Model.Message' 宣佈已經配置了相互矛盾的映射信息」}

+0

你如何計劃,以保持LastMessage財產正確的數據? – 2014-09-12 14:49:19

+0

這種關係對我來說很混亂,是一對一的關係嗎?如果是的話,哪一個是委託人?或者你可能需要的僅僅是一對多的簡單對象,一個博客有很多消息,博客不必擁有lastmessage,你可以在UI中管理它,'blog.Messages.OrderByDescending(..)。FirstOrDefault( )' – 2014-09-12 14:59:05

回答

0

下面是修復,我除去導航屬性上使用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")); 
+0

我知道這是兩年前的答案,但我遵循這個答案,並在博客映射如何博客模型有能力引用自己的行.WithRequired(t => t.Blog)? – 2017-04-01 11:31:56

1

的問題是您已經映射了Message類的「Blog」屬性兩次。在BlogMap類,你在這裏定義它:

HasOptional(t => t.LastMessage) 
       .WithRequired(t => t.Blog) 
       .Map(t => t.MapKey("LastMessageId")); 

這告訴EF,博客屬性是LastMessageId關係的「迴歸」的一面。

在MessageMap類,你在這裏定義它:

HasRequired(t => t.Blog) 
     .WithOptional() 
     .Map(t => t.MapKey("BlogId")); 

這是說博客屬性表示BlogId關係。

我懷疑第二個是你真正想要的,和第一關係的WithRequired()線應與.WithOptional()這樣的替換:

HasOptional(t => t.LastMessage) 
       .WithOptional() 
       .Map(t => t.MapKey("LastMessageId"));