所以我正在编写一个“半通用”类,它使用签名一遍又一遍地适合相同的模式
public class BaseSupportRepo<TEntity, TDto> where TEntity : class where TDto : class
使用此类的所有存储库都有一个属性,即 Name
我想要做的是编写一个函数,如果名称与某些输入匹配(但名称不是主键),该函数将返回 .Single() 。
现在,如果这是一个非通用函数,那就很容易了
.Single(g => g.Name == name)
但是,由于这是一个泛型函数,因此无法使用 .Name 属性,因为 TEntity 可能没有任何属性 Name。
EF 中是否有任何函数可以允许类似于:-
.Single(string key, string value)
这将使我能够绕过这个要求。
最佳答案
创建接口(interface):
public interface IEntityWithName
{
string Name { get; set;}
}
并将您的存储库更改为:
public class BaseSupportRepo<TEntity, TDto> where TEntity : class, IEntityWithName
where TDto : class
如果您有使用 edmx 文件生成的代码,您可以更改生成类的 T4 模板以实现 IEntityWithName
或创建部分类,如下所示:
public partial class SomeEntity : IEntityWithName
{
}
然后您可以编写一个可以使用名称
的查询
关于c# - 没有 lambda 表达式的 Entity Framework 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786495/