EF和LINQ 调用存储过程

来源:互联网 发布:淘宝网装饰腰带 编辑:程序博客网 时间:2024/06/06 16:27

好久没有更新文章了,最近项目比较忙都没什么时间来分享最近的问题。 今天遇到一个超级傻逼的问题。C#中调用存储过程,自己code也10来年了,这应该是很简单的问题了。今天有2个新的api,一个只有1个参数, 一个有10多个参数,先前没有注意到对象类型, 以为是EF的DbContext,结果后来才发现是LINQ的DataContext对象。以前调用存储过程都是靠设计界面封装成方法。 现在designer界面有500多张表, 几年没有维护了,大家要修改什么东东都是直接改代码。所以这里以后台代码调用存储过程为例。

EF调用存储过程

  using (AdventureWorks2014Entities aw=new AdventureWorks2014Entities())            {                int ret = aw.Database.ExecuteSqlCommand("EXEC [HumanResources].[uspUpdateEmployeeLogin] @BusinessEntityID,@OrganizationNode,@LoginID,@JobTitle,@HireDate,@CurrentFlag ",                    new SqlParameter("@BusinessEntityID",10),                    new SqlParameter("OrganizationNode",DBNull.Value),                    new SqlParameter("LoginID", @"adventure-works\michael6"),                    new SqlParameter("JobTitle", "Research and Development Manager23"),                    new SqlParameter("HireDate", DateTime.Now),                    new SqlParameter("CurrentFlag",true)                    );            }

注意这里的ExecuteSqlCommand第一个参数是字符串,这个字符串必须包含参数,如这里的@BusinessEntityID,其次这里的SqlParameter里面的参数名是可以包含@符号也可以不包含

LINQ调用存储过程

  using (AWDataClassesDataContext aw=new AWDataClassesDataContext())            {                int BusinessEntityID=10;                string OrganizationNode = null; //0x5AE178                string LoginID=@"adventure-works\michael6";                string JobTitle="Research and Development Manager12";                DateTime HireDate=DateTime.Now;                bool CurrentFlag=true;                string sql = string.Format(" EXEC [HumanResources].[uspUpdateEmployeeLogin] @BusinessEntityID={0},@OrganizationNode={1},@LoginID=N'{2}',@JobTitle=N'{3}',@HireDate=N'{4}',@CurrentFlag=N'{5}'"                    , BusinessEntityID.ToString(), "NULL", LoginID.ToString(), JobTitle.ToString(), HireDate.ToString(), CurrentFlag.ToString());                var ret = aw.ExecuteCommand(sql);                //var ret=aw.ExecuteCommand("EXEC [HumanResources].[uspUpdateEmployeeLogin] @BusinessEntityID={0},@OrganizationNode={1},@LoginID={2},@JobTitle={3},@HireDate={4},@CurrentFlag={5}"                //    , BusinessEntityID, null, LoginID, JobTitle, HireDate, CurrentFlag);             } 
ExecuteCommand方法的后面传值的参数不能是object对象,所以我这里只能拼接SQL字符串。 大家可能注意到这里调用存储过程与普通的sql语句没什么区别,只不过它的sql是调用存储过程如:EXEC [HumanResources].[uspUpdateEmployeeLogin] @BusinessEntityID=10,@OrganizationNode=NULL,@LoginID=N'adventure-works\michael6',@JobTitle=N'Research and Development Manager',@HireDate=N'2015/6/29 22:30:15',@CurrentFlag=N'True'这样的sql语句是比较危险的(可能有sql注入)。如果参数可能为Null,那么sql语句 还得动态拼接,比new SqlParameter("OrganizationNode",DBNull.Value)这种写法麻烦多了。我用反编译工具并没有看到DataContext里面的具体实现。看来LINQ to SQL真的是该淘汰了。
0 0