gpt4 book ai didi

c# - 使用 LINQ for Entity Framework 将实体转换为通用方法中的已实现接口(interface)

转载 作者:可可西里 更新时间:2023-11-01 08:10:03 25 4
gpt4 key购买 nike

我有一个通用方法来查询 EF 中 TEntity 类型的对象。如果 TEntity 实现特定接口(interface),我想将条件添加为 where 子句。我的方法是:

public TEntity GetByUserID(Guid userID)
{
var query = this.DbSet;
if (typeof (TEntity).IsImplementationOf<IDeletableEntity>())
{
query = query
.Where((x => !((IDeletableEntity)x).IsDeleted);
}
return query
.FirstOrDefault(x => x.UserID == userID);
}

IsImplementationOf<>() 顾名思义就是返回 true/false 的方法。

当我为实现 IDeletableEntity 的实体地址运行此命令时,出现错误:

Unable to cast the type 'Address' to type 'IDeletableEntity'. LINQ to Entities only supports casting EDM primitive or enumeration types.

我有什么想法可以解决 LINQ 的这个限制吗?

最佳答案

这是一个可行的解决方案:

public TEntity GetByUserID(Guid userID, params Include<TEntity>[] includes)
{
var query = this.DbSet;
query = Where<IDeletableEntity>(query, x => !x.IsDeleted);
return query
.FirstOrDefault(x => x.UserID == userID);
}

public static IQueryable<TEntity> Where<TPredicateWellKnownType>(IQueryable<TEntity> query, Expression<Func<TPredicateWellKnownType, bool>> predicate)
{
if (typeof(TEntity).IsImplementationOf<TPredicateWellKnownType>())
{
query = ((IQueryable<TPredicateWellKnownType>)query)
.Where(predicate)
.Cast<TEntity>();
}
return query;
}

关于c# - 使用 LINQ for Entity Framework 将实体转换为通用方法中的已实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com