EntityFramework 6在多对多关系上创建具有现有外键错误的新记录

时间:2014-09-28 21:38:30

标签: entity-framework entity-framework-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都会尝试创建一个唯一约束异常的新国家/地区记录。关于如何防止国家被拯救的任何想法?

1 个答案:

答案 0 :(得分:1)

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

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);
}