Entity framework 插入/更新多个对象
我有以下课程:Entity framework 插入/更新多个对象,entity-framework,Entity Framework,我有以下课程: public class Location { public int Id { get; set; } public string Description { get; set; } public string CarId { get; set; } public Car Car { get; set; } } public class Car { public string Id { get; set; } public st
public class Location
{
public int Id { get; set; }
public string Description { get; set; }
public string CarId { get; set; }
public Car Car { get; set; }
}
public class Car
{
public string Id { get; set; }
public string Color { get; set; }
}
还有一个观点:
<div>@Html.LabelFor(location => location.Description)</div>
<div>@Html.EditorFor(location => location.Description)</div>
<div>@Html.LabelFor(location => location.Car.Id)</div>
<div>@Html.EditorFor(location => location.Car.Id)</div>
<div>@Html.LabelFor(location => location.Car.Color)</div>
<div>@Html.EditorFor(location => location.Car.Color)</div>
它在“db.SaveChanges”中中断,因为它说“无法在对象“dbo.Car”中插入重复的密钥”
如果删除“db.Location.Add(locacao);”,因此,它对汽车(插入和更新)的效果非常好,但数据库中没有添加任何位置
如何在数据库中没有汽车id时插入新车,在有id时更新,并插入新位置?
Add
方法始终添加对象图中的所有实体,以便db.car.Add(location.car)
和db.location.Add(location)
都插入位置和汽车
试试这个:
db.Location.Add(locacation);
// You can also use another way to find if you are working with a new Car
// like location.Car.Id == 0
if (db.Car.Any(c => c.Id == location.Car.Id))
{
db.Entry(location.Car).State = EntityState.Modified;
}
db.SaveChanges();
db.Location.Add(locacation);
// You can also use another way to find if you are working with a new Car
// like location.Car.Id == 0
if (db.Car.Any(c => c.Id == location.Car.Id))
{
db.Entry(location.Car).State = EntityState.Modified;
}
db.SaveChanges();