使用EF处理嵌套表

时间:2014-11-14 19:21:13

标签: c# database entity-framework

物业:

  1. 我按此顺序有3个表:Company -> Person -> Phone
  2. Company可以有多个Person,可以有多个Phone
  3. 他们都incremental INTPK
  4. 他们之间有明确的关系,因此Phoneid_phone& id_company& id_person PK。{/ li>

    使用案例

    1. 用户希望添加Company Person Phone
    2. 问题:

      1. 如果我没有父母的Person,如何向Company添加PK? (Phone
      2. 也是如此

2 个答案:

答案 0 :(得分:3)

上下文将跟踪对子集合的添加

var phone = new Phone() { //whatever };
var person = new Person() { //whatever };
person.Phones.Add(phone);

var company = new Company() { //whatever };
company.People.Add(person);

dbContext.Companies.Add(company);
dbContext.SaveChanges();

只要您定义了关系,它就会自动设置正确的外键等。

以下是代码优先的示例

public class Company
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id;
    // other properties
    public virtual Collection<Person> People { get; set; }
}

public class Person
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id;
    // Other properties
    [ForeignKey("Company")]
    public int CompanyId { get; set; }
    public virtual Company Company { get; set; }
    public virtual Collection<Phone> Phones { get; set; }
}

更新:您可以以类似方式添加其他子项,您只需先获取实体

var db = new DbContext();
var company = db.Companies.FirstOrDefault(x => x.Id == 1);
if(company != null)
{
    var person = new Person() { // blah };
    company.People.Add(person);
    db.SaveChanges();
}

答案 1 :(得分:2)

只做

company.Persons.Add(new Person
    {
        //set Person properties here but dont worry about PK - EF sorts this out for you
    });
你甚至可以这样做:

company.Persons.Addcnew Person
    {
        //set Person properties here but dont worry about PK - EF sorts this out for you
        PhoneNumbers= new PhoneNumber[]
        {
            new PhoneNumber() {/*..*/ }
        }
    });