简体   繁体   English

使用EF处理嵌套表

[英]Dealing with nested tables with EF

Premises: 物业:

  1. I have 3 tables in this order: Company -> Person -> Phone 我按此顺序有3张桌子: Company -> Person -> Phone
  2. A Company can have multiple Person that can have multiple Phone . 一个Company可以有多Person ,也可以有多个Phone
  3. They all have incremental INT as PK . 它们都具有incremental INT作为PK
  4. They have an indentified relationship, so Phone have id_phone & id_company & id_person as PK . 他们之间的关系已经确定,因此Phone id_phoneid_companyid_personPK

Use Case: 用例:

  1. User wants to add a Company with a Person with a Phone . 用户想添加一个拥有PhonePersonCompany

Problem: 问题:

  1. How can I add a Person to a Company if I don't have the parent's PK ? 如果没有父母的PK如何将Person添加到Company (the same happens to Phone ) Phone

the context will track the additions made the child collections 上下文将跟踪添加的子集合

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

As long as you've defined the relationship, it will automatically set the correct foreign keys etc. 只要您定义了关系,它将自动设置正确的外键等。

Here's an example for code first 这是代码优先的示例

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

UPDATE: you can add additional children in a similar manner, you just have to fetch the entity first 更新:您可以通过类似的方式添加其他子代,只需先获取实体

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

Just do 做就是了

company.Persons.Add(new Person
    {
        //set Person properties here but dont worry about PK - EF sorts this out for you
    });

you can even do: 您甚至可以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM