raj*_*jin 5 c# asp.net-core-mvc ef-core-2.0
我有两班一对一的关系
public class Foo
{
public int FooId { get; set; }
public string Description { get; set; }
public ICollection<Bar> Bars { get; set; }
}
public class Bar
{
public int FooId { get; set; }
public Foo Foo { get; set; }
public int BarId { get; set; }
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想编辑一个Foo条目并需要添加新的Bar
var foo = _context.Foos.Include(b => b.Bars).FirstOrDefault(x => x.FooId == 8);
foo.Description = "changed";
_context.Entry(foo).State = EntityState.Modified;
foo.Bars.Add(new Bar() { Description = "new one",FooId=8,Foo=foo});
foreach (var b in foo.Bars)
_context.Entry(b).State = b.BarId == 0 ? EntityState.Added : EntityState.Modified;
_context.SaveChanges();
return View();
Run Code Online (Sandbox Code Playgroud)
我得到错误:
InvalidOperationException:在尝试将实体的状态更改为“已修改”时,实体类型“ Bar”的属性“ BarId”具有临时值。显式设置永久值,或确保将数据库配置为为此属性生成值
| 归档时间: |
|
| 查看次数: |
5308 次 |
| 最近记录: |