Tool:Visual Studio 2013 Ultimate Update 2 OS:Windows 8.1
.NET Framework : 4.5.x
Entity Framework : 6.0版以上
ASP.NET MVC 5
使用Entity Framework時,除了使用LINQ Expression以及擴充方法之外,還可以偷偷下SQL語法,不過你要自行小心SQL Injection問題。
若要在Entity Framework之中執行SQL,可以叫用SqlQuery方法,例如以下在MVC Controller之中使用以下SQL程式碼:
private PhotoSharingDB db = new PhotoSharingDB();
public async Task<ActionResult> Search( ) {
var sql = "select * from photos where Title like 'B%'";
var r = await db.Photos.SqlQuery(sql).ToListAsync( );
return View( "Search" , r );
}
var sql = "select * from photos where Title like 'B%'";
var r = await db.Photos.SqlQuery(sql).ToListAsync( );
return View( "Search" , r );
}
若要使用參數的話,可以將程式改為:
public async Task<ActionResult> Search( string term ) {
var sql = "select * from photos where Title like @p0 +'%'";
var r = await db.Photos.SqlQuery( sql , term ).ToListAsync( );
return View( "Search" , r );
}
var sql = "select * from photos where Title like @p0 +'%'";
var r = await db.Photos.SqlQuery( sql , term ).ToListAsync( );
return View( "Search" , r );
}
沒有留言:
張貼留言