[英]Entity Framework 6 update a table and insert into foreign key related tables
不安靜確定如何為這個標題寫標題,如果不准確,可以隨意編輯。
舉一個例子,我想要完成的是更新表foo中的記錄,然后在后續表中創建新記錄,其中foo表PK為外鍵,請考慮一對多關系。
如何更新具有外鍵約束的表並在這些后續表中創建新的相關記錄?
目前我正在使用Entity Framework 6到.Add和.Attach實體到上下文並將它們保存到數據庫中。
編輯
為了進一步澄清我想要實現的目標,下面的對象是一個減少的例子,我試圖保存到上下文中。 如果我試圖在“Billy Bob”創建之后添加intObj,因為他已經購買了一輛新車,另一項服務,或者他的輪胎已經改變,它將創建一個新的Billy Bob記錄(重復)和相應的相關表。
intObj.FirstName = "Billy";
intObj.Lastname = "Bob";
intObj.Important = 100;
intObj.LastSeen = DateTime.Now.Date;
intObj.Cars = new List<Car>{
new Car{
Model = "Commodore",
Make = "Holden",
YearMade = DateTime.Today.Date,
Odometer = 15000,
EmailWordCount = 500,
TyreStatuss = new List<TyreStatus>{
new TyreStatus{
Tyre1 = "Good",
Tyre2 = "Good",
Tyre3 = "Okay",
Tyre4 = "Okay"
}
},
Services = new List<Service>{
new Service{
Cost = "$500",
Time = "2 Days",
Date = DateTime.Today
}
},
}
};
謝謝
在下面的代碼片段中,您有Employee類,它引用了另外兩個實體:Assignment和一個Country的集合。
像EF,NHibernate等ORM有一個稱為傳遞持久性的特性,也就是說,如果一個對象(賦值和國家)被一個持久的(Employee)引用,那么賦值和國家最終也將成為持久性的,在EF的情況下,SaveChanges方法在Context中被調用,而不是你明確地保存它們。
public class Employee
{
public virtual Guid Id { get; protected set; }
public virtual string EmployeeNumber { get; set; }
public virtual Country BirthCountry { get; set; }
private ICollection<Assignment> _assignment = new List<Assignment>();
public virtual ICollection<Assignment> Assignments
{
get
{
return _assignment;
}
set
{
_assignment= value;
}
}
}
public class Assignment
{
public virtual Guid Id { get; protected set; }
public virtual DateTime BeginTime { get; set; }
public virtual DateTime EndTime { get; set; }
public virtual string Description{ get; set; }
}
public class Country
{
public virtual Guid Id { get; protected set; }
public virtual string Name { get; set; }
}
//Somewhere in your program
private void SaveAllChanges()
{
_db = new EFContext();
//Creating a new employee here, but it can be one loaded from db
var emp = new Employee { FirstName = "Emp Name",
LastName = "Emp Last", EmployeeNumber = "XO1500"
};
emp.BirthCountry = new Country { Name = "Country1" };
emp.Assignment.Add(new Assignment{ BeginTime = DateTime.Now,EndTime=DateTime.Now.AddHours(1) });
//Only employee is explicitly added to the context
_db.Employees.Add(emp);
//All the objects in the employee graph will be saved (inserted in this case) in the db.
_db.SaveChanges();
}
}
編輯:
這與我上面的代碼非常相似,一旦創建了“Billy Bob”,你只需要更新它,包括他購買的任何新服務;
偽代碼:
var bob = _db.Clients.SingleOrDefault(c=> c.Id = "Bob Row Id")
//Bob buy a car:
bob.Cars.Add(new Car()...)
//...and change tire 1 from an old car
var car = bob.Cars.SingleOrDefault(c=> c.Id = "Car Row Id")
car.TireStatus.Tire1 = "New"
....
//Persist all changes
//Existing objects will be updated..., and the new ones created in this process will be inserted
_db.SaveChanges()
如果這澄清了你的想法,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.