【发布时间】:2012-06-17 05:17:12
【问题描述】:
我有多个查询,如下所示:
var query = from a in EntityAs
select new EntityASmall()
{
// Common Stuff:
Id = a.Id,
Name = a.Name,
ShortName = a.ShortName,
// Specific to EntityA:
ASpecificProperty1 = a.1,
ASpecificProperty2 = a.2
};
var query = from b in EntityBs
select new EntityBSmall()
{
// Common Stuff:
Id = b.Id,
Name = b.Name,
ShortName = b.ShortName,
// Specific to EntityB:
BSpecificProperty1 = b.1,
BSpecificProperty2 = b.2
};
EntityA 和 EntityB 都派生自具有 Id、Name 和 ShortName 属性的公共基类。 EntityASmall 和 EntityBSmall 也是如此。我有很多看起来像这样的查询,所以我想做一些速记查询,先把常见的东西排除在外。我发现了一个有点前途的扩展方法,看起来像这样:
public static TSource SetCommonProperties<TSource>(this TSource input, EntityBaseClass entity, Action<TSource> updater) where TSource : EntitySmallBase
{
input.Id = entity.Id;
input.Name = entity.Name;
input.ShortName = entity.Name;
updater(input);
return input;
}
我可以这样使用它:
var query = from a in EntityAs.AsEnumerable()
select new EntityASmall().SetCommonProperties(a, x =>
{
ASpecificProperty1 = x.1;
ASpecificProperty2 = x.2;
});
注意AsEnumerable()。没有它,我会得到“无法将带有语句体的 lambda 表达式转换为表达式树”,我大致猜测这意味着它正在尝试将 Action 部分转换为 LINQ-to-SQL 的表达式。看起来AsEnumerable() 将集合带到了本地,它完全可以工作。很抱歉这篇冗长的帖子,但是有没有任何表达方式来编写这个可以与 LINQ-to-SQL 和实体框架一起使用的方法?提前致谢。
【问题讨论】:
-
EntityAs是IQueryable<>? -
你不能写一个泛型方法
ProjectOntoSmall接受TEntity类型的参数并将其转换为TEntitySmall吗?如果你对这些必须从基类型派生的类型参数施加约束,我猜它会起作用。
标签: c# linq entity-framework linq-to-sql expression