entity-framework - EntityFramework 6 在多对多关系上使用现有外键错误创建新记录

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

最佳答案

在下面的代码中,您将创建一个新的 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/

相关文章:

asp.net - 将多个数据源组合到一个 ASP.NET 转发器?

asp.net - WebAPI 中的 DTO 和投影

c# - 如何修复 Asp.NET MVC 中的 "This dictionary requires a model item of type"?

c# - 无法使用独立关联将可选外键设置为空

用于 EF 核心中数据迁移的 MongoDbContext?

c# - 缓存数据库查询的最佳方法是什么

c# - 使用 EF Code First Migration 将新的必填字段添加到其中一个表中

c# - Entity Framework 代码优先 - 列 ID 无效

c# - Entity Framework COUNT 性能不佳

c# - Entity Framework 错误 : The ForeignKeyAttribute on property is not valid