LinqToSql:如何创建一个符合DRY的投影?

时间:2010-04-09 12:42:21

标签: linq-to-sql projection

只是想知道是否有办法从LINQ to SQL投影类型中取出一些重复。

示例:

表:地址

字段:AddressID,HouseNumber,Street,City,State,Zip,+ 20 more

Class MyAddress: AddressID,HouseNumber,Street(仅限3个字段)

LINQ:

from a in db.Addresses
select new MyAddress
{
  AddressID = a.AddressID,
  HouseNumber = a.HouseNumber,
  Street = a.Street
}

以上查询完美无缺,我理解为什么这样的内容将返回每行中的所有20多个字段:

from a in db.Addresses
select new MyAddress(a);

class MyAddress
{
  public MyAddress(Address a)
  {
    this.AddressID = a.AddressID,
    this.HouseNumber = a.HouseNumber,
    this.Street = a.Street
  }
}

这引出了我的问题:

是否可以实现某种辅助函数或扩展方法从LINQ模型“映射”到MyAddress,但只返回查询结果中的必要字段而不是所有字段?

1 个答案:

答案 0 :(得分:2)

from a in db.Addresses
select new MyAddress
{
  AddressID = a.AddressID,
  HouseNumber = a.HouseNumber,
  Street = a.Street
}

该查询只会在生成的SQL中选择请求的字段。

重复使用该类型的函数如下所示:

public IQueryable<MyAddress> ProjectAddress(IQueryable<Address> addresses)
{
    return from a in addresses
           select new MyAddress
           {
               AddressID = a.AddressID,
               HouseNumber = a.HouseNumber,
               Street = a.Street
           };
}

可以这样使用:

return ProjectAddress(db.Addresses);

我认为函数看起来像:

public static Expression<Func<Address, MyAddress>> ToMyAddress()
{
    return a => new MyAddress { AddressID = a.AddressID, 
                                HouseNumber = a.HouseNumber,
                                Street = a.Street
                              };
}