EF:MVC:ASP:TPH 错误 - 存储更新、插入或删除...行数 (0)。实体...修改或删除...刷新ObjectStateManager
错误消息:“存储更新、插入或删除语句影响了意外数量的行 (0)。实体加载后可能已被修改或删除。刷新 ObjectStateManager 条目。”
大家好,
我使用 SQL 紧凑数据库在 MVC 和 EF 中创建了 Code First TPH(每个层次结构表)。
这是类图/层次结构:
Client 和 SalesRep 都继承 BaseUser班级。密钥是“UserID”,它使用数据注释 [Key]
进行编码(我知道“ID”也应该设置它)
这就是我所在的位置:我可以为数据库播种有一些条目。当我尝试在播种方法中设置“UserID”时,它似乎忽略它并仅按数字顺序应用 UserID...(对我来说似乎没问题?)
此外,这是我的 DbContext
public class SiteDB:DbContext
{
public DbSet<BaseUser> AllUsers { get; set; }//enable TPH
public DbSet<SalesRep> SalesReps { get; set; }
public DbSet<Client> Clients { get; set; }
}
接下来,
我为客户端创建了一个控制器 - >具有强类型 Razor 视图的 ClientsController。有了这个。我现在为客户提供了 CRUD。我可以毫无问题地创建新客户端,但是当我尝试编辑客户端条目时,我收到上述错误消息。
我确实注意到一些有趣的事情,我单步执行了代码,并且错误发生在 db.SaveChanges(); 上。
当客户端传回 ActionResult Edit 方法时,UserID=0!奇怪吗?我不确定这是否是一个错误,或者是否是导致此问题的实际问题。
感谢您的帮助。谢谢!
Error Message: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
Hello All,
I've created a Code First TPH(Table Per Hierarchy) within MVC and EF with a SQL compact db.
Here's the Class diagram/Hierarchy:
Client and SalesRep both inherit the BaseUser class. The Key is "UserID" and it's coded with the Data Annotation [Key]
(I'm aware that 'ID' should set it as well)
Here's where I'm at: I can seed the database with a few entries. When I try to set the "UserID" in the seeding method it seems to ignore it and just apply the UserID in numerical order...(Seems ok to me?)
furthermore here's my DbContext
public class SiteDB:DbContext
{
public DbSet<BaseUser> AllUsers { get; set; }//enable TPH
public DbSet<SalesRep> SalesReps { get; set; }
public DbSet<Client> Clients { get; set; }
}
Next,
I have created a controller for Clients -> ClientsController with strongly typed Razor Views. With this. I now have a CRUD for the Clients. I can create new Clients without any issue, but when I try to edit a Client entry, I get the error message stated above.
I did notice something interesting I stepped through the code and the error is happening on the db.SaveChanges();
When the client is passed back into the ActionResult Edit method the UserID=0! Bizarre? I'm not sure if this is a bug or if it's an actual issue that's causing this.
Your help with this is appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要修改实体,您需要从数据库中获取它:当您在编辑操作中传回修改后的值时,您需要从
db
对象中检索实体,通过 ID 获取它,应用修改后的值值并保存。这里有一个例子:
To modify an entity you need to get it from the database: when you pass back the modified values in the Edit action you need to retrive the entity from the
db
object, getting it by ID, apply the modified values and save it.Here an example: