我有以下两个模型和 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];
对我做错了什么有任何想法吗?谢谢你的帮助。