所以我有两个对象
// 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);
}
关于entity-framework - EntityFramework 6 在多对多关系上使用现有外键错误创建新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089920/