EntityFramework 6 Creating new Record with existing foreign key error on Many-to-many relationships

entity-framework entity-framework-6

Question

I now possess two items.

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

So when I try to add a new record to Record, problems start to occur. CountryCollection using the code below

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

The result is that every time I try to create a new Country record using this method, EF tries to create a new record with a unique constraint error. Any suggestions on how to stop nations from being saved?

1
2
9/28/2014 9:38:29 PM

Accepted Answer

ZZZ_tmp
1
9/29/2014 4:20:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow