欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Data Access FAQ (二)

程序员文章站 2022-05-30 18:58:44
...

这里是ASP.NET Data Access FAQ的第二部分: LINQ How can I implement a transaction in LINQ? A: You can use TransactionScope class in LINQ to implement a transaction. Its a new function in .NET Framework 2.0 to provide an implicit way to impl

这里是ASP.NET Data Access FAQ的第二部分:

LINQ

How can I implement a transaction in LINQ?

A: You can use TransactionScope class in LINQ to implement a transaction. It’s a new function in .NET Framework 2.0 to provide an implicit way to implement a transaction. You can use it in LINQ as shown below:

using (TransactionScope scope = new TransactionScope())

{

try

{

……….

ctx.SubmitChanges();

……….

ctx.SubmitChanges();

}

catch (Exception ex)

{

Response.Write("Error happens, Transaction class will automaticlly roll back!");

}

scope.Complete();

}

You need to reference the System.Transactions assembly and add the namespace ‘System.Transactions’. Also, you need to make sure the windows service-“Distributed Transaction Coordinator Service” is running.

Related link:

http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx

How can I use left join in LINQ.

A: You can use the keywords “join” and “into” to implement left join in LINQ. Please take a look at following example:

var sel = from u in

join p inon u.TagID equals p.TagID into UP

from p in UP.DefaultIfEmpty()

select new

{

UT = u.TagID,

UT1 = u.Text,

UT2 = p.Info

};

What’s the difference between List and IQueryable?

A: You can return LINQ query result as type of both List and IQueryable. But there are some differences between these two types.

List will create a new list object in memory immediately to persist data. If there’re any associations in this table, the related information will be null. But IQueryable will not retrieve the data until you iterate the data source – use foreach, databind, ToList and so on. When there’s an association in this table, the related information will not be null and can be used. Please take a look at following example to understand the differences between them.

// Return List will fail when referring to related UserInfos object

ListUser> users = res.ToListUser