EF和LINQ 調用存儲過程


好久沒有更新文章了,最近項目比較忙都沒什么時間來分享最近的問題。 今天遇到一個超級傻逼的問題。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真的是該淘汰了。


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM