设置一般属性我有一个看起来像这样多个查询:如何使用LINQ选择
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到SQL的表达式。看起来像AsEnumerable()
把它收集在本地的地方它的全部工作。对于长篇大论的文章感到抱歉,但是有没有什么表达式方法可以用来编写可以与LINQ-to-SQL和Entity Framework一起使用的表达式?提前致谢。
'EntityAs'是'IQueryable <>'? –
难道你不能写一个泛型方法'ProjectOntoSmall',它需要一个'TEntity'类型的参数并将其转换为'TEntitySmall'?如果你对这些类型参数施加约束,而这些参数必须从基类型中派生出来,那我想可能会起作用。 –