您好,登錄后才能下訂單哦!
缺點:Entity FrameWork 沒有提供獲取不同層上的對象的方式,無助于創建多層上的解決方案,可以結合WCF實現分層
核心概念:
邏輯層,SSDL store schema definition language描述數據庫表及其關系
概念層,CSDL conceptual schema definition L 描述 實體及關系
映射層 MSL mapping Specification L 把CSDL實體類型定義映射到SSDL
查詢對象的三種方法
1. Entity SQL
using (var data = new Formula1Entities())
{
string country = "Brazil";
ObjectQuery<Racer> racers = data.CreateQuery<Racer>(
"SELECT VALUE it FROM ([Formula1Entities].[Racers]) AS it WHERE it.Country = @Country",
new ObjectParameter("Country", country));
foreach (var r in racers)
{
Console.WriteLine("{0} {1}", r.Firstname, r.Lastname);
}
}
2.QueryBuilder
類似于LINQ,但Linq的參數是委托,而QueryBuilder的參數是字符串
可以用Find(),GroupBy(),OrderBy()等方法,
using (var data = new Formula1Entities())
{
string country = "Brazil";
ObjectQuery<Racer> racers = data.Racers.Where("it.Country = @Country", new ObjectParameter("Country", country));
Console.WriteLine(racers.CommandText);
Console.WriteLine(racers.ToTraceString());
}
3. Linq to Entities
因為實體對象都繼承于ObjectQuery<T>,而該類實現了IQueryable接口
using (var data = new Formula1Entities())
{
var racers = from r in data.Racers
where r.Wins > 40
orderby r.Wins descending
select r;
foreach (Racer r in racers)
{
Console.WriteLine("{0} {1}", r.Firstname, r.Lastname);
}
}
增刪改查CRUD的實現
using (var data = new Formula1Entities())
{
var jaime = new Racer
{
Firstname = "Jaime",
Lastname = "Alguersuari",
Country = "Spain",
Starts = 0
};
data.Racers.AddObject(jaime);
//添加
Racer niki1 = data.Racers.Where("it.Country='Austria' && it.Lastname='Berger'").First();
data.Racers.DeleteObject( niki1 );
//刪除
Racer niki2 = data.Racers.Where("it.Country='Austria'").OrderBy("it.Wins DESC").First();
niki2.Stars++;//修改
int changes = 0;
try
{
changes += data.SaveChanges();
//提交到數據源
}
catch (OptimisticConcurrencyException ex)
{
data.Refresh(RefreshMode.ClientWins, ex.StateEntries);
changes += data.SaveChanges();
}
}
//懶惰加載
using (var data = new NorthwindEntities())
{
data.ContextOptions.LazyLoadingEnabled = false;
int a = data.Customers.Count();
foreach (Customer customer in data.Customers.Include("Orders"))
{
Console.WriteLine("{0}", customer.CompanyName);
bool a2 = customer.Orders.IsLoaded;
// if (!customer.Orders.IsLoaded)
// {
// customer.Orders.Load();
}
foreach (Order order in customer.Orders)
{
Console.WriteLine("\t{0} {1:d}", order.OrderID, order.OrderDate);
}
}
}
data.ContextOptions.LazyLoadingEnabled = false;
LazyLoadingEnabled 懶惰加載,意思是在訪問對象時,會自動加載對象的相關屬性
foreach (Customer customer in data.Customers)
LazyLoadingEnabled 默認為true,若設為false,則需要使用
Include("Orders")) 稱為預先加載
customer.Orders.Load();(延遲加載
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。