Exception while passing enum value to stored procedure using Entity Framework 6

↘锁芯ラ 提交于 2020-01-15 11:14:28

问题


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.


回答1:


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)




回答2:


Change

new SqlParameter("Group", grp)

as

   if(grp.HasValue)
   {
      new SqlParameter("Group", Convert.ToInt32(grp.Value));
   }
   else
   {
     new SqlParameter("Group", DBNull.Value);
   }

should work.



来源:https://stackoverflow.com/questions/45396682/exception-while-passing-enum-value-to-stored-procedure-using-entity-framework-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!