Linq 介绍

    Linq两种不同写法

     

    语言的发展,LINQ可以更加自然的操作数据

    IEnumreable<string> query =  from s in names where s.length == 5 orderby s select s.toupper();
    
    IEnumreable<string> query = names.where(s=>s.length ==5).OrderBy(s=>s).select(s=>s.toupper());
    例:where中的lambda表达式可以理解为下面的这个委托
    Func<string,bool> filter = new delegate{return s.length == 5 }
     
    public static class Enumerable{
    public static IEnumerable<T> where<T>(
           this IEnumerable<T> source, Func<T, bool> predicate){
       foreach(T item in source)
           if(predicate(item))
           yield return item;
    }}

Linq to sql

 

实体类映射

[Table(Name = "xxxx")]
public class xxxx
{
	[Column(IsPrimaryKey = true)]
	public string id;
	[Column]
	public string Name;
}
 
 

DataContext数据上下文对象

 

DataContext db = new DataContext(constring);
Table<xxxx> t  = db.GetTable<xxxx>;
var result = from c in t
		 select c;

DataContext非常相数据库链接对象,但是他为linq to sql提供了更多支持

 

数据表的关系

一对多: 集合关系, EntitySet

多对一: 引用关系, EntityRef

示例

category与product, 是一对多关系

在category类中定义: private EntitySet<products>; [Association(storage = “product”), otherkey = “categoryid”]

在products类中定义:  private EntityRef<category>; [Association(storage = “category”), otherkey = “categoryid”]

 

数据表的更改

 

DataContext.SubmitChanges();

 

Linq查询执行过程

 

var result = …….

result变量仅仅是对linq查询的一个描述,而非执行结果,换言之,linq查询语句并不立执行得到结果,而将查询缓存在变量result中

public interface IQueryable: IEnumerable{
Type ElementType{get;}
Expression Expression{get;}

IQueryable CreateQurey(Expression exp);
object Execute(Expression exp);
}

public interface Iqueryable<T>: IEnumerable<T>, IQueryable, IEnumerable{
IQueryable<TElement> CreateQurey<TElement>(Expression exp);
TResult Execute<TRest>(Expression exp);
}
 
IQuerybale<T>只是查询表示,类似于SQLCOMMAND等命令表示,IQueryqble<T>表达查询的是一个Expression强类型结构。
posted @ 2009-09-21 07:44  refeiner  阅读(255)  评论(0编辑  收藏  举报