对于多对多关系的联结表,是否有一种方法不经常调用SaveChanges?

时间:2018-11-20 14:17:59

标签: c# entity-framework-6

我需要在多对多关系的联接表中有一个额外的字段,如下所示:

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

在关系的末尾有这两个类:

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

但是,在使用它时,我不得不在上下文上调用SaveChanges太多次,主键和外键无法获取它们的值,如本例所示:

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

我希望最后只有一个SaveChanges(),但似乎无法获取... 如果这些中间的SaveChanges()被删除,我将得到以下异常:

  

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

有什么想法吗?

关于, 胡安

0 个答案:

没有答案