I need to have an extra field in the junction table of a many-to-many relationship, like so:
public class PersonCompany
{
public int PersonId { get; set; }
public int CompanyId { get; set; }
public Person Person { get; set; }
public Company Company { get; set; }
public DateTime HireDate { get; set; }
}
with these 2 classes at the ends of the relationship:
public class Company
{
public int CompanyId { get; set; }
public string Name { get; set; }
public virtual ICollection<PersonCompany> PersonCompanies { get; set; }
}
public class Person
{
public Person()
{
PersonCompanies = new List<PersonCompany>();
}
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<PersonCompany> PersonCompanies { get; set; }
}
Yet when using it, I have to call SaveChanges on the context too many times for the primary and foreign keys to get their values, like in this example:
private static void AddPersonWithCompanies()
{
using (var context = new Context())
{
var person = new Person
{
LastName = "Dent",
FirstName = "Juan",
IsActive = false
};
context.People.Add(person);
context.SaveChanges();
var comp1 = new Company() { Name = "Universal" };
var comp2 = new Company() { Name = "Lehmann" };
context.Companies.Add(comp1);
context.Companies.Add(comp2);
context.SaveChanges();
var pc1 = new PersonCompany() { Company = comp1, Person = person, HireDate = DateTime.Today };
var pc2 = new PersonCompany() { Company = comp2, Person=person, HireDate = DateTime.Today };
person.PersonCompanies.Add(pc1);
person.PersonCompanies.Add(pc2);
context.SaveChanges();
}
}
I would like to have only one SaveChanges() at the end but can't seem to get it... I get the following exception if these intermediate SaveChanges() are removed:
System.Data.Entity.Infrastructure.DbUpdateException
HResult=0x80131501
Message=Unable to determine the principal end of the 'Chapter3.CSharp.Company_PersonCompanies' relationship. Multiple added entities may have the same primary key.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Chapter3.CSharp.Program.AddPersonWithCompanies() in C:\Users\Juan Dent\OneDrive\CSharp\Code First-Code Bundle\B03947_03_Code\Chapter3.CSharp\Program.cs:line 47
at Chapter3.CSharp.Program.Main(String[] args) in C:\Users\Juan Dent\OneDrive\CSharp\Code First-Code Bundle\B03947_03_Code\Chapter3.CSharp\Program.cs:line 14
Any ideas?
Regards, Juan
User contributions licensed under CC BY-SA 3.0