第七節:EF Core調用SQL語句和存儲過程(2.x和3.x寫法)


一. 查詢類

  EFCore2.x中用 FromSql 方法,EFCore3.x中用 FromSqlRaw 方法,二者使用起來基本一致。

1.說明

  A. SQL查詢必須返回實體的所有屬性字段。

  B. 結果集中的列名必須與屬性映射到的列名相匹配。

  C. SQL查詢不能包含關聯數據

  D. 除Select以為的其它SQL語句無法運行。

2.調用SQL語句的幾種情況

  A. 基本的原生SQL查詢

  B. 利用$內插語法進行傳遞

  C. 原生SQL與linq語法相結合

  D. 利用SqlParameter進行參數化查詢

代碼分享:(2.x版本的寫法)

 1 {
 2                 using (EFDB01Context db = new EFDB01Context())
 3                 {
 4                     //1.基本的原生SQL查詢
 5                     var userList1 = db.Set<T_UserInfor>().FromSql("select * from T_UserInfor where id!='123'").ToList();
 6 
 7                     //2.利用$內插語法進行傳遞
 8                     var myId = "2fc343069e0a4a559b62b08d5999dbcd";
 9                     var userList2 = db.Set<T_UserInfor>().FromSql($"select * from T_UserInfor where id= {myId}").ToList();
10 
11                     //3.原生SQL與linq語法相結合
12                     var userList3 = db.Set<T_UserInfor>().FromSql($"select * from T_UserInfor")
13                         .Where(u => u.id == "2fc343069e0a4a559b62b08d5999dbcd")
14                         .ToList();
15                     var userList4 = db.Set<T_UserInfor>().FromSql($"select * from T_UserInfor")
16                         .Where(u => u.id != "1111")
17                         .OrderBy(u => u.addTime)
18                         .ToList();
19 
20                     //4.利用SqlParameter進行參數化查詢
21                     SqlParameter[] paras ={
22                                              new SqlParameter("@id","2fc343069e0a4a559b62b08d5999dbcd"),
23                                              new SqlParameter("@userName","ypf"),
24                                         };
25                     var userList5 = db.Set<T_UserInfor>().FromSql("select * from T_UserInfor where id=@id and userName=@userName", paras).ToList();
26                 }
27 }

3.調用存儲過程的幾種情況

  可以利用SqlParameter傳遞參數,防止sql注入。

  A.不含任何參數

  B.含多個輸入參數

  C.含輸入參數和輸出參數

 用到的表結構:

 對應的生成存儲過程的代碼:

 1 USE [EFDB01]
 2 
 3 --事先准備:插入兩條數據
 4 select * from T_UserInfor
 5 truncate table T_UserInfor
 6 insert into T_UserInfor values('01','ypf','',12,'2019-08-08')
 7 insert into T_UserInfor values('02','ypf2','',30,'2019-09-08')
 8 
 9 -- 1. 不含任何參數存儲過程
10 if (exists (select * from sys.objects where name = 'GetAll'))
11     drop proc GetAll
12 go
13     create proc GetAll
14 as
15     select * from T_UserInfor;
16 
17 -- 調用
18 exec GetAll;
19 
20 
21 --2. 含多個輸入參數的存儲過程
22 if (exists (select * from sys.objects where name = 'GetALLBy'))
23     drop proc GetALLBy
24 go
25     create proc GetALLBy(
26         @id varchar(32),
27         @userName varchar(20)
28     )
29 as
30     select * from T_UserInfor where id=@id and userName=@userName;
31 
32 exec GetALLBy @id='01',@userName='ypf';
33 
34 --3. 含輸出參數的存儲過程
35  if (exists (select * from sys.objects where name = 'GetSpecial'))
36     drop proc GetSpecial
37 go
38     create proc GetSpecial(
39         @userName varchar(32),
40         @count int output
41     )
42 as
43     select @count=count(*) from T_UserInfor;
44     select * from T_UserInfor where userName= @userName;
45 
46 go
47 declare @myCount int;
48 exec GetSpecial 'ypf',@myCount output;
49 select @myCount as myCount;

對應EF調用的代碼:(2.x的寫法)

 1             {
 2                 using (EFDB01Context db = new EFDB01Context())
 3                 {
 4                     //1. 不含任何參數存儲過程
 5                     var data1 = db.Set<T_UserInfor>().FromSql("GetAll").ToList();
 6 
 7                     //2. 含多個輸入參數的存儲過程
 8                     SqlParameter[] para ={
 9                                            new SqlParameter("@id","01"),
10                                            new SqlParameter("@userName","ypf")
11                                   };
12                     var data2 = db.Set<T_UserInfor>().FromSql("GetALLBy @id,@userName", para).ToList();
13 
14                     //3. 帶輸出參數的存儲過程
15                     //把輸出參數單獨拿出來聲明
16                     SqlParameter myCount = new SqlParameter("@count", SqlDbType.Int);
17                     myCount.Direction = ParameterDirection.Output;
18                     //把輸出參數放到數組里
19                     SqlParameter[] para2 ={
20                                            new SqlParameter("@userName","ypf"),
21                                            myCount
22                                      };
23                     var data3 = db.Set<T_UserInfor>().FromSql("exec GetSpecial @userName,@count out", para2).ToList();
24                     //通過輸出參數在數組中的位置來獲取返回值。
25                     var count = para2[1].Value;
26 
27                 }
28             }

 

二. 其它類

  EFCore2.x中用 ExecuteSqlCommand 方法,EFCore3.x中用 ExecuteSqlRaw 方法,二者使用起來基本一致。

1.說明

  主要用於調用除了查詢外其它的SQL語句。

2.調用SQL語句的情況

  A. 基本的原生SQL查詢

  B. 利用$內插語法進行傳遞

  C. 利用SqlParameter進行參數化查詢

代碼分享:(2.x的寫法)

 1             {
 2                 using (EFDB01Context db = new EFDB01Context())
 3                 {
 4 
 5                     //1.增加
 6                     int result1 = db.Database.ExecuteSqlCommand("insert into T_UserInfor values('01','test1','男',21,'2019-09-09')");
 7 
 8                     //2. 修改
 9                     SqlParameter[] paras ={
10                                                      new SqlParameter("@id","01"),
11                                                      new SqlParameter("@userSex","未知"),
12                                                 };
13                     int result2 = db.Database.ExecuteSqlCommand("update T_UserInfor set userSex=@userSex where id=@id", paras);
14 
15                     //3. 刪除
16                     var myId = "01";
17                     int result3 = db.Database.ExecuteSqlCommand($"delete from T_UserInfor where id={myId}");
18 
19                     //4. 其它指令
20                     int result4 = db.Database.ExecuteSqlCommand("truncate table T_UserInfor");
21                 }
22             }

3.調用存儲過程的情況

 存儲過程代碼

--4. 非查詢類的存儲過程
if (exists (select * from sys.objects where name = 'DoSome'))
    drop proc DoSome
go 
    create proc DoSome(
        @id varchar(32)
    )
as
    begin transaction
 begin try
        insert into T_UserInfor values(@id,'ypf','',12,'2019-08-08');
        delete from T_UserInfor where id='02'
    commit transaction
 end try
 begin catch
    rollback transaction
 end catch

 exec DoSome '03'

EF的調用代碼 (2.x的寫法)

 1             {
 2                 using (EFDB01Context db = new EFDB01Context())
 3                 {
 4                     SqlParameter[] para ={
 5                                            new SqlParameter("@id",Guid.NewGuid().ToString("N")),
 6                                      };
 7                     int n = db.Database.ExecuteSqlCommand("DoSome @id", para);
 8                     if (n > 0)
 9                     {
10                         Console.WriteLine("操作成功");
11                     }
12                     else
13                     {
14                         Console.WriteLine("沒有更多數據進行處理");
15                     }
16                 }
17             }

 

 

 

!

  • 作       者 : Yaopengfei(姚鵬飛)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 聲     明1 : 本人才疏學淺,用郭德綱的話說“我是一個小學生”,如有錯誤,歡迎討論,請勿謾罵^_^。
  • 聲     明2 : 原創博客請在轉載時保留原文鏈接或在文章開頭加上本人博客地址,否則保留追究法律責任的權利。
 


免責聲明!

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



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