Entity Framework是微軟出品的高級ORM框架,大多數.NET開發者對這個ORM框架應該不會陌生。本文主要羅列在.NET(ASP.NET/WINFORM)應用程序開發中使用Entity Framework直接執行SQL語句或者存儲過程的一些代碼片段。具體請見以下正文:
1.使用SqlQuery在已知的實體上執行SQL查詢語句
using (var context = new MyDBContext())
{
var posts = context.Posts.SqlQuery("SELECT * FROM dbo.Posts").ToList(); }
這里的Posts必須是程序項目或者引用中已聲明的實體類,ToList()是必須的,否則SQL查詢將不會被執行。
注意:如果使用原始的SQL查詢語句,請一定要注意處理SQL注入攻擊相關的安全問題。
2.使用SqlQuery在已知的實體上執行存儲過程
using (var context = new MyDBContext())
{
var posts = context.Posts.SqlQuery("dbo.spGetTopPosts").ToList(); }
這里的Posts必須是程序項目或者引用中已聲明的實體類,ToList()是必須的,否則SQL查詢將不會被執行。以上代碼將執行存儲過程: spGetTopPosts
3.使用SqlQuery在已知實體上執行帶參數的存儲過程
using (var context = new MyDBContext())
{
var postID = 99; var posts = context.Posts.SqlQuery("dbo.spGetTopPosts @p0", postID).Single(); }
這里的Posts必須是程序項目或者引用中已聲明的實體類,Single()是必須的,否則SQL查詢將不會被執行。以上代碼將執行存儲過程: spGetTopPosts,並帶一個傳入參數postID
4.使用SqlQuery在未知實體上執行SQL查詢語句
using (var context = new MyDBContext())
{
var postTitles = context.Database.SqlQuery<string>("SELECT Title FROM dbo.Posts").ToList(); }
5.使用SqlQuery執行帶參數的SQL查詢語句
這是一種相比更安全的,可避免SQL注入攻擊的執行原始SQL查詢語句的方式
using (var context = new MyDBContext())
{
var userSuppliedAuthor = new SqlParameter("@author", "Adi"); context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @author", userSuppliedAuthor); }
這里的SQL語句將查詢Posts表,所以用到了typeof(Post)。如果JOIN語句來查詢不同的兩張表的話,就需要寫一個內部類來返回SQL語句的查詢結果。
以下則是一個使用JOIN連接查詢的具體實例。
假如有Posts,Category,Posts_Category這三張表。Posts_Category是Post表中Post Id列以及Category表中Category Id列的映射表。如果我們執行如下的JOIN連接SQL查詢:
internal class MappingData
{
public string CategoryTitle { get; set; } public string PostTitle { get; set; } public long? MappingId { get; set; } } using (var context = new MyDBContext()) { var userSuppliedId = new SqlParameter("@PostId", PostID); string sqlQuery = @"select c.Name CategoryTitle, pcm.Id MappingId, p.Title PostTitle from Posts_Categories pcm join Categories c on pcm.CategoryId = c.Id join Posts p on pcm.PostId = p.Id where pcm.PostId =@PostId"; var Results = db.Database.SqlQuery<MappingData>(sqlQuery,userSuppliedId).ToList(); }
查詢結果將是所有給定Post的Categories列表。
6.使用ExcuteSqlCommand在未知實體上執行更新操作
using (var context = new MyDBContext())
{
context.Database.ExecuteSqlCommand( "UPDATE dbo.Posts SET Title = 'Updated Title' WHERE PostID = 99"); }
總結:以上的SqlQuery和ExecuteSqlCommand方法均是DbContext對應數據庫實例的方法,如果是執行原始的未經處理的SQL語句時,請一定注意SQL注入攻擊等安全性問題!!!
7. 存儲過程
7.1 示例(1)
create proc pro_Add @i int, @j int, @he int output as set @he = @i+@j
System.Data.SqlClient.SqlParameter[] parameters2 = { new System.Data.SqlClient.SqlParameter("@i",100), new System.Data.SqlClient.SqlParameter("@j",100), new System.Data.SqlClient.SqlParameter("@he", System.Data.SqlDbType.Int) }; parameters2[2].Direction = System.Data.ParameterDirection.Output; System.Data.Common.DbCommand cmd = DbContext.Database.Connection.CreateCommand(); cmd.CommandText = "pro_Add"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddRange(parameters2); if (cmd.Connection.State != System.Data.ConnectionState.Open) cmd.Connection.Open(); cmd.ExecuteNonQuery(); string output1 = parameters2[2].Value.ToString(); cmd.Connection.Close(); string output2 = parameters2[2].Value.ToString();
7.2 示例(2)
create proc pro_Add @i int, @j int, @he int output as set @he = @i+@j select @he go
System.Data.SqlClient.SqlParameter[] parameters = { new System.Data.SqlClient.SqlParameter("@i",100), new System.Data.SqlClient.SqlParameter("@j",100), new System.Data.SqlClient.SqlParameter("@he", System.Data.SqlDbType.Int) }; parameters[2].Direction = System.Data.ParameterDirection.Output; var slt = this.DbContext.Database.SqlQuery<int>("exec pro_Add @i,@j,@he output", parameters); slt.ToList(); int AllCount = Int32.Parse(parameters[2].Value.ToString());
8. 執行SQL語句
//示例1. System.Data.SqlClient.SqlParameter[] parameters = { }; var slt = this.DbContext.Database.SqlQuery(typeof(BadWordFilter),"select top 100 * from BadWordFilter", parameters); foreach( var item in slt ) { BadWordFilter badword = item as BadWordFilter; string word = badword.badWordContent; } //示例2. System.Data.SqlClient.SqlParameter[] parameters = { new System.Data.SqlClient.SqlParameter("@id",ID)}; var slt = this.DbContext.Database.SqlQuery<BadWordFilter>("select top 1 * from BadWordFilter where badWordID=@id", parameters); BadWordFilter item = slt.First(); //示例3. System.Data.SqlClient.SqlParameter[] parameters = { }; var slt = this.DbContext.Database.SqlQuery<int>("select count(*) from BadWordFilter", parameters); int AllCount = slt.First();