缺点: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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。