物业:
Company -> Person -> Phone
Company
可以有多个Person
,可以有多个Phone
。incremental INT
为PK
。Phone
有id_phone
& id_company
& id_person
PK
。{/ li>
醇>
使用案例
Company
Person
Phone
。问题:
Person
,如何向Company
添加PK
? (Phone
)答案 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() {/*..*/ }
}
});