【问题标题】:GetEntity from Generic DataRepository not working通用数据存储库中的 GetEntity 不起作用
【发布时间】:2014-05-20 14:42:39
【问题描述】:

我正在尝试使用基本的 CRUD 操作创建一个通用存储库。我的 GetEntity 函数有问题

protected override T GetEntity(FinancialDataContext entityContext, int id)
{
    var query = (from e in entityContext.Set<T>()
                 where e.Id == id
                 select e);
    var result = query.FirstOrDefault();
    return result;
}

错误出现在我的 e."Id" 上,并说“T 不包含 'Id' 的定义,并且找不到接受 'T' 类型的第一个参数的扩展方法 'Id'(缺失参考?)

如何引用 ID 的“承诺”?还是有其他解决方法?

【问题讨论】:

  • 考虑为所有实体引入一些通用抽象类,比如BaseEntity,它定义了 Id 属性。那么T可以声明为where T : BaseEntity
  • 我不确定你的意思@Andrei...

标签: c# asp.net .net generics repository


【解决方案1】:

如果您对实体的声明方式有一定程度的控制,那么您可以执行以下操作。创建一个声明Id 属性的基类:

public abstract class BaseEntity
{
    public in Id { get; set; }
}

然后让你的所有实体继承这个类(确保从它们中删除 Id 声明,因为它已经在基类中):

public class Entity1 : BaseEntity

现在,在您的通用存储库中,您实际上可以对如何键入它进行一些限制:

public class Repository<T> where T : BaseEntity

这本身很好,但它也使您可以访问Id(以及此BaseEntity 可能具有的任何其他常见属性)。

【讨论】:

  • id 属性是使用实体框架创建的。这正是我需要的,谢谢!!
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 2013-05-06
  • 2016-12-21
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
相关资源
最近更新 更多