日期:2014-05-20  浏览次数:20929 次

一个关于LINQ的问题
本帖最后由 stszd604 于 2012-07-13 14:20:06 编辑 场景  fcategory 在 t_products是编码  他的名称在 t_prod_category表中 

目的  fcategory 显示的是t_prod_category的  fcatename

问题  当在 LINQPAD中  强行指定了返回类  红色部分程序就出错了  
      如果去掉红色部分 使用匿名类型是完全可以的 
      因为这段代码在  数据访问层 所以。。。 需要指定返回类型 




from p in t_products
join c in t_prod_category
on p.fcategory equals c.fcategory
select new t_products
{
        fsku = p.fsku,
        fcategory= c.fcatename,
        fproname=p.fproname,
        funit_price= p.funit_price,
        fdescription= p.fdescription
}



完整方法体 如下 

public  IQueryable<t_products>  GetAll()
{

var res =  
       from p in t_products
       join c in t_prod_category
       on p.fcategory equals c.fcategory
       select new t_products
       {
               fsku = p.fsku,
               fcategory= c.fcatename,
               fproname=p.fproname,
               funit_price= p.funit_price,
               fdescription= p.fdescription
       };
return res;



}


------解决方案--------------------

public IEnumerable<t_products> GetAll()
{

var res =   
  (from p in t_products
  join c in t_prod_category
  on p.fcategory equals c.fcategory
  select new t_products
  {
  fsku = p.fsku,
  fcategory= c.fcatename,
  fproname=p.fproname,
  funit_price= p.funit_price,
  fdescription= p.fdescription
  }).Select(x=>new t_products(){fsku=x.fsku,fcategory=x.fcategory,...});
return res;



}



------解决方案--------------------
你可以自己定义一个综合性的Model,如下

 public class TestMode
    {
        public int no { get; set; }
        public string code { get; set; }
    } 


IQueryable<TestMode> result = from a in EF.T_Province join b in EF.T_City on a.ID equals b.Province_ID select new TestMode { no = a.ID, code = b.Name };