使用Entity Framework将枚举值传递给存储过程时异常6 [英] Exception while passing enum value to stored procedure using Entity Framework 6

查看:96
本文介绍了使用Entity Framework将枚举值传递给存储过程时异常6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

 公开枚举组
{
服务= 1,
Dev = 2,
支持= 3
}

我正在使用它在一个模型中

  public class Invoice 
{
public int ID {get;组; }
public DateTime MyDate {get;组; }
public string Name {get;组; }
public Group?组{get;组; }
}

现在我使用上面的模型类来调用存储过程: p>

  public ...方法(组grp)
var Details = this.Context.Database.SqlQuery< Invoice>( spname @ ID,@ MyDate,@ Name,@ Group,
......
new SqlParameter(Group,grp),
).ToList();

组是 int 在SQL Server中键入。 p>

我收到一个例外:


将nvarchar转换为int

b $ b

如果 grp 参数中有值



当我的参数中有null时,我得到异常,枚举应该是nullable类型。但是我已经做了我,e 组?



存储过程本身使用execute命令在数据库中正常工作。

解决方案

尝试

  SqlParam eter sqp = null; 
if(grp.HasValue)
sqp = new SqlParameter(Group,grp.Value)
else
sqp = new SqlParameter(Group,DBNull.Value)
...

然后在您的调用中使用sqp查询



为什么这么复杂?你的grp是组合?因此可以是null,但是没有一个很好的单行方式将其转换为int(不可空)或null(可空)


I have an enum

public enum Group
{
        Services = 1,
        Dev = 2,
        Support = 3
}

I am using it in a model

public class Invoice
{
        public int ID { get; set; }
        public DateTime MyDate { get; set; }
        public string Name { get; set; }
        public Group? Group { get; set; }
}

Now I am calling a stored procedure using the above model class:

public ... method(Group grp)
 var Details = this.Context.Database.SqlQuery<Invoice>("spname @ID,@MyDate,@Name,@Group,
 ......
                    new SqlParameter("Group", grp),
                    ).ToList();

Group is of int type in SQL Server.

I get an exception:

Error converting nvarchar to int

in case when there is value in the grp parameter

I get exception when null is there in parameter that enum should be nullable type..but I have made it i,e Group?

The stored procedure itself is working correctly in database using execute command.

解决方案

Try

SqlParameter sqp = null;
if(grp.HasValue)
  sqp=new SqlParameter("Group", grp.Value)
else
  sqp=new SqlParameter("Group", DBNull.Value)
...

Then use sqp in your call to query

Why this complexity? Well.. your grp is type Group? and hence can be null but there isn't a good single line way of converting it to either an int (not nullable) or null (nullable)

这篇关于使用Entity Framework将枚举值传递给存储过程时异常6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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