35

以下は私のモデルです:

public class TMUrl
{
    //many other properties

    //only property with type Keyword
    public List<Keyword> Keywords{get;set;} 
}

public class Keyword
{
   //many other properties

   //only property with type TMUrl
   public List<TMUrl> Urls{get;set;}
}

明らかに、両方のエンティティに多対多の関係があります。この関係についてエンティティ フレームワークに伝えるために流暢な API を選択しました。

modelBuilder.Entity<TMUrl>
               .HasMany(s => s.Keywords)
               .WithMany(s => s.URLs).Map(s =>
                {
                    s.MapLeftKey("KeywordId");
                    s.MapRightKey("UrlId");
                    s.ToTable("KeywordUrlMapping");
                });

しかし、私がするとき

url.Keywords.Add(dbKey); //where url is object of TMUrl, 
                         //dbKey is an existing/new object of Keyword
db.SaveChanges();

例外が発生します

An error occurred while saving entities that do not expose foreign key 
properties for their relationships....

内部例外:

The INSERT statement conflicted with the FOREIGN KEY constraint   
"KeywordMaster_Keyword". The conflict occurred in database "DbName", 
table "dbo.KeywordMaster", column 'Id'.The statement has been terminated.

しかし、反対側から構成を追加すると、すべて正常に動作します。すなわち

modelBuilder.Entity<KeyWord>
         .HasMany(s => s.URLs)
         .WithMany(s => s.Keywords)
         .Map(s =>
               {
                  s.MapLeftKey("KeywordId");
                  s.MapRightKey("UrlId");
                  s.ToTable("KeywordUrlMapping");
               });

どうして?。ここで読んだエンティティと他の多くの場所で両方のエンティティから構成を追加する必要がある理由は、エンティティの1つの構成で十分です。

関係に関係する両方のエンティティの構成を追加する必要がある場合はどうなりますか?

これを理解する必要があります。どうして。助けてください。

4

1 に答える 1