我想使用LINQ查询一些实体:
public class Link: Entity, IAggregateRoot
{
public Guid RelationId { get; private set; }
public Guid ConstructionId { get; private set; }
public virtual Relation Relation { get; private set; }
public virtual Construction Construction { get; private set; }
private Link()
{
}
}
public class Relation: Entity, IAggregateRoot
{
public string Number { get; private set; }
public Guid PersonId { get; private set; }
public Guid RelationTypeId { get; private set; }
public virtual Person Person { get; private set; }
public virtual RelationType RelationType { get; private set; }
[NotMapped]
public int ContextKey { get; set; }
private Relation()
{
}
}
我有一个查询,该查询通过提供构造ID并使用Link实体来返回关系。该查询如下所示,并且可以正常工作:
public IQueryable<Relation> GetRelationsByConstructionId(Guid constructionId)
{
var links base.Get(x => x.Construction.ConstructionId == constructionId);
var relations = links.Include(x => x.Relation)
.Select(x => x.Relation)
.Include(x => x.Person)
.Include(x => x.RelationType);
return relations;
}
在关系中,我有一个NotMapped元素ContextKey,我想在查询调用中设置此ContextKey(例如,我想将其设置为30)。基本上,我想做这样的事情来扩展我使用的查询:
public IQueryable<Relation> GetRelationsByConstructionId(Guid constructionId)
{
var links base.Get(x => x.Construction.ConstructionId == constructionId);
var relations = links.Include(x => x.Relation)
.Select(x => x.Relation)
.Include(x => x.Person)
.Include(x => x.RelationType);
var updatedRelations = relations.ForEachAsync(x => x.ContextKey = 30);
return updatedRelations;
}
这当然不起作用,因为在 ForEachAsync 之后, updatedRelations 的类型为 Task ,并且预期的返回类型必须为可查询的<关系> 。
如何使查询正常工作并以正确的 IQueryable
答案 0 :(得分:3)
这是我反对未映射属性的原因之一-它们不适合LINQ to Entities查询。
您可以使用以下LINQ to Objects技巧:
var updatedRelations = relations
.AsEnumerable()
.Select(x => { x.ContextKey = 30; return x; })
.AsQueryable();
但请注意,这不是真正的EF Core可查询的,因此将在AsEnumerable()
之前的查询具体化结果中在内存中执行进一步的操作,如过滤,排序,分页等。
答案 1 :(得分:0)
我自己通过更新查询进行了如下修复:
public IQueryable<Relation> GetRelationsByConstructionId(Guid constructionId)
{
var links base.Get(x => x.Construction.ConstructionId == constructionId);
var relations = links.Include(x => x.Relation)
.Select(x => x.Relation)
.Include(x => x.Person)
.Include(x => x.RelationType);
relations.ToList().ForEach(x => x.ContextKey = 30);
return relations;
}