检查实体框架中的插入或更新是否成功
在 ADO.NET 中,ExecuteNonQuery()“对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数”(http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx)
在 EF v1 中,context.SaveChanges() 方法返回“调用 SaveChanges 时处于已添加、已修改或已删除状态的对象数量”。 (http://msdn.microsoft.com/en-us/library/bb739065。 aspx)
请告诉我,当向上下文添加或更新多个实体(或单个实体)并调用 context.SaveChanges() 方法时,如何检查实际 INSERT 或 UPDATE 是否成功。
如果没有异常,我们是否可以假设 INSERT(s) 或 UPDATE(s) 成功?
谢谢
In ADO.NET, ExecuteNonQuery() "For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command" (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx)
In EF v1, context.SaveChanges() method returns "The number of objects in an Added, Modified, or Deleted state when SaveChanges was called." (http://msdn.microsoft.com/en-us/library/bb739065.aspx)
Please tell, when multiple entities (or single entity) are added or updated to context and context.SaveChanges() method is called, how to check if actual INSERT or UPDATE was successful.
Can we assume if there was NO exception that INSERT(s) or UPDATE(s) was successful ?
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,如果没有异常,您可以假设语句执行成功。
Yes, if there is no exception you may assume that the statements executed successfully.
在 EntityFramework 中,
SaveChangesAsync()
返回一个 int。所以你可以检查它是否是
> 0
或不是。如果
SaveChangesAsync()
发生某些情况,它将返回受影响的行数,这意味着if value > 0
然后true。简单地说,您可以有以下场景:INSERT
UPDATE
DELETE
在您的方法中,现在您可以简单地检查更改是否成功:
对于一个简单的MVC场景:
您可以对更新和更新进行相同的练习。删除
In EntityFramework,
SaveChangesAsync()
returns an int.So you can check if it is
> 0
or not.If something happens with
SaveChangesAsync()
it will return the number of effected rows and this meansif value > 0
then true. So simply, you can have below scenerio:INSERT
UPDATE
DELETE
And in your methods, now you can simply check if that change is success or not:
For a simple MVC scenerio:
You can do the same practice for Update & Delete
也许这不是问题的直接答案,但可能会有所帮助。
默认情况下,当调用 SaveChanges 方法时,所有命令都封装在一个 DbTransaction 中 (Julia Lerman,实体框架编程)。所以,要么所有命令都会成功执行,要么两者都不执行。这是了解插入、更新或删除是否成功的一种方法。
Maybe this is not direct answer to the question, but may help.
By default all commands are encapsulated in one DbTransaction when SaveChanges method is called (Julia Lerman, Programming Entity Framework). So, or all commands will be successfully executed, or neither. That's one way to know if insert, or update or delete was successful.
定义变量 SaveStatus
var SaveStatus=context.SaveChanges()
那么你可以通过获取SaveStatus=1的值来知道创建是否完成,
如果“SaveStatus=0”,则表示没有创建或影响记录
define variable SaveStatus
var SaveStatus=context.SaveChanges()
then you can know if the creation has been done by getting the value of SaveStatus=1
in the case of "SaveStatus=0" it means no record has been created or affected