的情況下將跟蹤添增所製作的子集合
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; }
}
UPDATE:你可以以類似的方式添加其他的孩子,你只需要獲取實體第一
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();
}
假設你有一個'Company'的實例,你應該只能寫'myCompany.Persons.Add(myPerson)' – MikeH 2014-11-14 19:23:23
是的,我有這個實例。即使ID的值爲零,它也可以工作嗎? – 2014-11-14 19:30:46
是的,當你保存你的更改時,EF會照顧鑰匙 – MikeH 2014-11-14 19:34:04