您的位置:首页 > 数据库

.net 3.5 数据库开发 之 LINQ to SQL

2009-03-05 17:34 489 查看
Code 4-6

using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn))

{

conn.Open();

using (SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior,CloseConnection))

{

var result = context.Translate<Customers>(reader);

foreach (var item in result)

{

Console.WriteLine(item.CustomerID);

}

}

}

4、Deferring Load

当一次性的将Order和OrderDetail(两个之间存在Association)中的行取回,当访问Order时,它的明细信息并没有加载,只有在访问OrderDetail的属性时,明细才会被加载,这时每访问一个OrderDetail属性,程序就会发送一次SQL语句到数据库,这种方式成为Deffering Load。

这种方式好不好呢?这样根据情况来定,如果数据很多的话,这样可以很大的节省内存空间,而如果数据很少,这种方式的效率就相对较低了。所以要根据实际情况进行选择。

如何关闭Deferring Load功能:

程序4-7

NorthwindDataContext context = new NorthwindDataContext();

context.DeferredLoadingEnable = false;

System.Data.Linq.DataLoadOptions loadOptions =

new System.Data.Linq.DataLoadOptions();

loadOptions.LoadWith<Orders>(o => o.Order_Details);

context.LoadOptions = loadOptions;

var result = from s1 in context.Orders

where s1.OrderDate > DateTime.Parse("2009/03/04")

select s1;

先设置DataContext的DeferredLoadingEnable属性为false,关闭DeferringLoad功能

然后创建DataLoadOptions对象,通过调用此对象的LoadWith或AssociateWith来指定哪些Entity Object要一次性加载那一个关联相关的Entity Object。

注意:1.不能在指定为DataContext的LoadOptions属性后再调用LoadWith函数:

如context.LoadOptions.LoadWith<Orders>(o => o.Order_Details); 是错误的

2.除了LoadWith函数外,之前也提过LoadOptions还有另外一个方法AssociateWith,此方法可以指定关联Entity Object时的过滤,可以和LoadWith搭配使用:

loadOptions.LoadWith<Orders>(o => o.Order_Details);

loadOptions.AssociateWith<Orders>(o => o.Order_Details.Where( p => p.productID == 60);

context.LoadOptions = loadOptions;

3.使用LoadWith时,不能出现循环的情况,如

loadOptions.LoadWith<Orders>( o => o.Order_Details);

loadOptions.LoadWith<Order_Details>(o => o.Orders); //这种做法是错误的

5.继承

Entity Oject 继承是ORM不可或缺的技术之一。具体的解释如下:

有三个类,People、Male、Female,数据库中有一张Persons表中有Name,Sex、Age字段,这三个类可以都和Persons表关联,以Sex属性进行区分,当sex = 1时,对应的实体为male,sex=2时,对应实体为female,sex = 0 则为people。这时,我们可以设置Male和Female继承自People,而People有Name、Sex和Age属性。其中Sex属性值就被成为“Discriminator Property”,而区分实体为People的Sex属性值成为“Basic class DiscriminatorProperty Value”,而区分实体为Male和Female的Sex属性值成为“Derived Class DiscriminatorProperty Value”。当实体的Sex属性值既不属于Male,也不属于Female和People时,那么该属性值就视“Inheritance Default”属性值所设置的实体而定。

.net 3.5 数据库开发 之 ADO.net Entity Framework
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐