前言
首先來簡單的復習一下如何使用Code First。
第一步還是先建立一個控制台的應用程序,然后通過Nuget添加Entity Framework。那么同時會給packages.config和App.config添加相應的配置。
第二步添加一個數據操作上下文實體類。添加兩個構造函數,並添加一個Person的實體類。 在App.config的配置文件中添加相應的數據鏈接配置。
第三步在調用即可生成相應的數據庫。
EFContext.cs
public class EFContext:DbContext
{
public EFContext()
: base("EFContext")
{ }
public EFContext(string connectionstring)
:base(connectionstring)
{
}
public DbSet<Person> Persons { get; set; }
}
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="EFContext" connectionString="Data Source=.;Database=EFContext;UID=sa;PWD=sa123;" providerName="System.Data.SqlClient"></add>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
package.config
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="EntityFramework" version="5.0.0" targetFramework="net45" /> </packages>
然后簡單的添加了一個實體類
public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
最終進行調用
static void Main(string[] args)
{
using (var db = new EFContext("EFContext"))
{
var persons = db.Persons.Where(t => t.PersonName == "aehyok").OrderByDescending(t => t.PersonId).ToList();
foreach (var p in persons)
{
Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
}
}
Console.ReadLine();
}
運行后控制台沒有數據顯示,但是在數據庫里可以查看到相應的數據庫EFContext和數據表People。
現在我們通過數據庫直接為上面建立的數據庫EFContext中的People表手動添加了幾條數據。

然后重新運行程序。可以發現有數據了。

此時可以發現我們的第一個簡答的查詢語句已經實現了。
一個數據庫上下文的生命周期隨着該對象的創建而開始,隨着對象的釋放(或GC回收)而結束,因此建議在開發過程中使用“Using”編碼方式,這樣就可以免去手動釋放對象的操作。另外對於數據庫連接的管理在EF中是透明的,我們一般不需要手動進行處理,當查詢一個對象時打開連接當處理完查詢的結果集之后會自動關閉連接。
Linq To Entity表達式查詢
查詢表達式是C#3.0新增的功能,它是由一組類似於T-SQL或XQuery聲明性語句組成,CLR並不能直接讀取這種查詢表達式而是在編譯時轉換為對應的方法調用。如下面的例子:
using (var db = new EFContext("EFContext"))
{
var persons = from p in db.Persons
where p.PersonName == "aehyok"
orderby p.PersonId descending
select p;
foreach (var p in persons)
{
Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
}
}
Console.ReadLine();
得到的結果同上面是一致的。
基於方法的查詢
基於方法的查詢事實上是一組對象的擴展方法,同Linq查詢不同的是這些方法可以直接被CLR識別並運行。
例如上面的方法我們可以轉換為如下代碼,他們的效果是一樣的,返回的都是“IQueryable”對象,這里的代碼其實也就是我們開始為創建數據庫測試的代碼
using (var db = new EFContext("EFContext"))
{
var persons = db.Persons.Where(t => t.PersonName == "aehyok").OrderByDescending(t => t.PersonId).ToList();
foreach (var p in persons)
{
Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
}
}
Console.ReadLine();
當然執行的結果還是一樣的。
原生SQL的查詢
EF還支持原生SQL查詢例如:
using (var db = new EFContext("EFContext"))
{
var persons = db.Persons.SqlQuery("select * from EFContext..People where PersonName='aehyok'");
foreach (var p in persons)
{
Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
}
}
Console.ReadLine();
可以直接通過SQL語句的拼接額,當然這里只是做了最簡單的實例。
不僅如此,EF還支持非實體類型的查詢:
using (var db = new EFContext("EFContext"))
{
var persons = db.Database.SqlQuery<string>("select PersonName from EFContext..People where PersonName='aehyok'");
foreach (var p in persons)
{
Console.WriteLine("The PersonName is {0} ", p);
}
}
當然也支持無返回值的SQL命令:
using (var db = new EFContext("EFContext"))
{
var persons = db.Database.ExecuteSqlCommand("update EFContext..People set Address='中國' where PersonName='aehyok'");
}
