c# - EntityFramework 存储库模板 - 如何在模板类中编写 GetByID lambda?

标签 c# entity-framework templates repository-pattern

我正在尝试为我目前正在处理的基于 Entity Framework 的项目编写一个通用的通用存储库模式模板类。 (高度简化的)界面是:

internal interface IRepository<T> where T : class
{
  T GetByID(int id);
  IEnumerable<T> GetAll();
  IEnumerable<T> Query(Func<T, bool> filter);
}

事实证明,GetByID 是 killer 。在实现中:

public class Repository<T> : IRepository<T>,IUnitOfWork<T> where T : class
{
  // etc...
  public T GetByID(int id)
  {
    return this.ObjectSet.Single<T>(t=>t.ID == id);
  }

t=>t.ID == id 是我正在努力解决的问题。甚至可以在没有类特定信息可用的模板类中编写 lambda 函数吗?

最佳答案

我定义了一个接口(interface):

public interface IIdEntity
{
    long Id { get; set; }
}


并修改了生成我的 POCO 类的 t4 模板,以便每个类都必须实现公共(public)接口(interface) IIdEntity 接口(interface)。

像这样:

using System.Diagnostics.CodeAnalysis;
public partial class User : IIdEntity
{
    public virtual long Id
    {
        get;
        set;
    }

通过此修改,我可以编写一个通用的 GetById(long id),如下所示:

public T GetById(long id)
{
    return Single(e => e.Id == id);
}

IRepository 定义如下:

/// <summary>
/// Abstract Base class which implements IDataRepository interface.
/// </summary>
/// <typeparam name="T">A POCO entity</typeparam>
public abstract class DataRepository<T> : IDataRepository<T>
    where T : class, IIdEntity
{

关于c# - EntityFramework 存储库模板 - 如何在模板类中编写 GetByID lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2941689/

相关文章:

c++ - 由具有不同数量参数的其他函数参数化的函数模板

c# - 为什么我应该只在应用程序生命周期的早期创建 MemoryCache?

c# - 是否可以使用 C# 交互模式?

c# - TcpClient:如何关闭并重新连接它?

c# - 在 Entity Framework 中合并

c++ - Clang VS VC++ :"error: declaration of ' T'阴影模板参数”

c++ - 如何解决不合格名称查找问题

c# - Foreach本身会加倍或三倍

c# - "The * field is required"当EF对象已经有字段

entity-framework - 带有 Sql Server Compact 3.5 SP2 的 Entity Framework 6?