【问题标题】:Entity framework query without lambda expression没有 lambda 表达式的实体框架查询
【发布时间】:2015-01-05 19:31:22
【问题描述】:

所以我正在编写一个“半通用”类,它一遍又一遍地与签名匹配相同的模式

public class BaseSupportRepo<TEntity, TDto> where TEntity : class where TDto : class

所有使用这个类的repos都有一个属性Name

我想做的是编写一个函数,如果名称与某些输入匹配(但名称不是主键),它将返回 .Single() 。

现在,如果这是一个非通用函数,那就很容易了,因为

.Single(g => g.Name == name)

但是,因为这是一个通用函数,所以不能使用 .Name 属性,因为 TEntity 可能没有任何属性 Name。

EF 中是否有任何函数可以允许类似于:-

.Single(string key, string value)

这可以让我绕过这个要求。

【问题讨论】:

  • 为什么不直接创建一个 INamedEntity { string Name } 和 where TEntity : INamedEntity 并让你的所有实体都实现 TEntity
  • 你能用Anonymous Types吗?

标签: c# entity-framework generics lambda


【解决方案1】:

创建接口:

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
{
}

然后您可以编写一个可以使用Name的查询

【讨论】:

  • 不幸的是,我无法使用实体类,因为它们是使用工具生成的:|
  • 如果实体是部分类,您可以将接口放在您自己文件的部分类中
【解决方案2】:

看看这个故事:Where can I find the System.Linq.Dynamic dll?。我相信 Dynamic.cs 是由 Microsoft 的某个人编写的,它允许您使用字符串而不是 lambdas 编写 Linq 查询。在我目前正在进行的项目中,它对我很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多