gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:42:40 26 4
gpt4 key购买 nike

我正在尝试为我目前正在处理的基于 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/

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