我有以下兩種型號及的DbContext:實體框架 - 通過改變更新關係外鍵
public class TestDbContext : DbContext
{
public IDbSet<Person> People { get; set; }
public IDbSet<Car> Cars { get; set; }
}
public class Person
{
public Person()
{
ID = Guid.NewGuid();
}
public Guid ID { get; set; }
public string Name { get; set; }
public virtual List<Car> Cars { get; set; }
}
public class Car
{
public Car()
{
ID = Guid.NewGuid();
}
public Guid ID { get; set; }
public string Name { get; set; }
public virtual Person Owner { get; set; }
}
我再聲明的人的名單和汽車的名單,第一輛車的所有者設置爲第一人名單:
List<Person> People = new List<Person>()
{
new Person() {Name = "bill", ID = new Guid("6F39CC2B-1A09-4E27-B803-1304AFDB23E3")},
new Person() {Name = "ben", ID = new Guid("3EAE0303-39D9-4FD9-AF39-EC6DC73F630B")}
};
List<Car> Cars = new List<Car>() { new Car() { Name = "Ford", Owner = People[0], ID = new Guid("625FAB6B-1D56-4F57-8C98-F9346F1BBBE4") } };
我保存這一關,以使用下面的代碼數據庫,並能正常工作。
using (TestDbContext context = new TestDbContext())
{
foreach (Person person in People)
{
if (!(context.People.Any(p => p.ID == person.ID)))
context.People.Add(person);
else
{
context.People.Attach(person);
context.Entry<Person>(person).State = System.Data.EntityState.Modified;
}
}
foreach (Car caar in Cars)
{
if (!(context.Cars.Any(c => c.ID == caar.ID)))
context.Cars.Add(caar);
else
{
context.Cars.Attach(caar);
context.Entry<Car>(caar).State = System.Data.EntityState.Modified;
}
}
context.SaveChanges();
}
如果我然後將車主更換爲第二人並再次運行代碼,車主屬性不會更新。
Cars[0].Owner = People[1];
任何想法,我在做什麼錯?謝謝你的幫助。
剛剛添加,我試圖實現什麼建議http://stackoverflow.com/questions/9382005/move-child-entities-to-a-new-parent-entity – user2697817
你是如何保存它?代碼在哪裏?你需要從DB重新加載'Cars',然後完成任務。 – zsong