我有多个查询如下所示:
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
属性的公共(public)基类。 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()
将集合带到了本地,它可以完全工作。很抱歉冗长的帖子,但是有没有任何表达式-y 的方式来编写这个可以与 LINQ-to-SQL 和 Entity Framework 一起使用的方法?提前致谢。
最佳答案
你想让你的代码变干,这总是好的,付出一些努力。也许你会得到你的方法与一些辛勤劳动和一些Expression
巫术,但也许你'我会喜欢这个链接:Stop using AutoMapper in your Data Access Code . (即使您不使用 AutoMapper)。
通过这项出色的工作,您将能够编写简洁的语句,例如:
context.EntityAs.Project().To<EntityASmall>();
context.EntityBs.Project().To<EntityBSmall>();
我自己用过这个,我真的很喜欢。
关于c# - 如何使用 LINQ 选择器设置通用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11054107/