处理实体框架中的SQL异常 [英] Handles SQL Exception from Entity Framework

查看:114
本文介绍了处理实体框架中的SQL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的sql存储过程中,我做一些插入和更新,在某些情况下会抛出主键或唯一的键冲突。

In my sql stored procedure, i do some insertion and updating which in some scenarios throws Primary Key or unique key violation.

当我尝试执行此过程ADO.net,.net应用程序也抛出异常,让我知道发生了错误。

When I try to execute this procedure from ADO.net, .net application also throws that exception and let me know that something wrong had happen.

但是当我尝试从EF执行这个过程时,它只是执行。

But when I try to execute this procedure from EF, it just executes. Neither it show anything nor update anything.

如何处理或通知用户发生错误的情况?

How should I handle or notify user that something wrong had happen?

Ado.Net代码

 SqlConnection sqlConnection = new SqlConnection(@"data source=database01; database=test; user id=test; password=test;");
        SqlCommand cmd = new SqlCommand("[uspUpdateTest]", sqlConnection);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("RunID", RunID);
        cmd.Parameters.AddWithValue("RunCode", RunCode);
        sqlConnection.Open();
        var str = cmd.ExecuteNonQuery();

实体框架代码是

 TestEntities context = new TestEntities();
        var str=context.UpdateRun(RunID, RunCode);


推荐答案

我非常确定,你必须设置一些返回在函数导入中键入(虚拟)。大多数时间是有意义的,因为如果你不这样做,你的方法名称不会出现在智能感知中,你将无法使用context.MethodName访问它。

I am very much sure, you must set some return type(dummy) in your function import. It makes sense most of the time, because if you don't do so, your method name does not appear in intellisense and you will no be able to access it using context.MethodName.

我的建议是,删除您的功能导入的返回类型并将其设置为无。使用上下文的 ExecuteFunction 方法执行您的方法。

My suggestion for you is, remove the return type of your Function Import and set it to none. Execute your method using ExecuteFunction method of context.

Context.ExecuteFunction(FunctionName,Parameters)。这绝对会抛出异常。

Context.ExecuteFunction(FunctionName,Parameters). It'll definitely throws the exception.

这篇关于处理实体框架中的SQL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆