筛选关联对象 :外键值 VS 导航属性

    

    

  关系如上所示,产品中的CategoryID可以为空,我想得到没有分类的产品,可以通过两种方法来实现

  1. Foreign Key Value:外键值为空

  2.Navigation Property:Navigation Property中的Category为空

 

  那么哪种方法更好呢,下面看下两种方法有什么区别 

     代码

                //Foreign Key Value
                var query1 = from p in context.Products
                            
where p.CategoryID != null 
                            select p;

                
//Navigation Property
                var query2 = from p in context.Products
                             
where p.Category != null
                             select p;

 

   两个linq查询语句,分别实现了相同的结果,但实现过程并不相同:

代码
Response.Write("Foreign Key Value:" + "<br/>" + ((ObjectQuery<Product>)query1).ToTraceString() + "<br/>");
Response.Write(
"Navigation Property:" + "<br/>"  +((ObjectQuery<Product>)query2).ToTraceString());

 

  

  结果如下:   可以看到,Navigation Property方法生成了一些没用的代码,相对的Foreign Key Value方法生成的代码更简洁,也更接近我们使用sql使用的代码。

  所以在这种情况的应用中使用外键来判断要更好一些。 

 

 

posted @ 2010-08-03 17:12  i'm zjz  阅读(625)  评论(0编辑  收藏  举报