EntityFramework 6在多对多关系上使用现有外键创建新记录时出错



所以我有两个对象

// First Object
public class Record{
   public int RecordId { get; set;} 
    public virtual ICollection<Country> CountryCollection { get; set; }
}

// Second Object
public class Country{
   public int CountryId { get; set;} 
   public virtual ICollection<Record> Records{ get; set; } 
   [Index("UI_CountryName", IsUnique = true)] 
   public string CountryName { get; set; }
}
..
// And my map configuration
public class RecordMap: EntityTypeConfiguration<Record>
{
    HasMany(r => r.CountryCollection)
            .WithMany(c => c.Records)
            .Map(t => t.ToTable("RecordCountryMap","dbo").MapRightKey("CountryId").MapLeftKey("RecordId"));
}

因此,当我尝试使用以下代码将新记录插入record.CountryCollection时,问题就出现了

 newRevisionRec.CountryCollection = new Collection<Country>();
        foreach (var country in record.Countries)
        {
            newRevisionRec.CountryCollection.Add(new Country
            {
                CountryId = country.CountryId,
                CountryName = country.CountryName,
            });
        }

最终发生的是,每次我这样做时,EF都试图创建新的国家记录,这是一个独特的约束例外。关于如何防止国家被拯救,有什么想法吗?

在下面的代码中,您正在创建一个新的Country对象,该对象将被Entity视为重复对象,因为它是管理关系的对象。

newRevisionRec.CountryCollection = new Collection<Country>();
foreach (var country in record.Countries)
{
    newRevisionRec.CountryCollection.Add(new Country
    {
        CountryId = country.CountryId,
        CountryName = country.CountryName,
    });
}

相反,你想把它已经知道的对象传给它,让它重用它们:

foreach (var country in db.Countries.Where(t => t. ...))
{
    newRevisionRec.CountryCollection.Add(country);
}

最新更新