【问题标题】:How to resolve generic repository and use it in a single variable?如何解析通用存储库并将其用于单个变量?
【发布时间】:2015-04-09 16:43:15
【问题描述】:

我正在尝试为具有相同列的表构建一些通用代码,但我在弄清楚如何使用通用“解析器”以便仅使用一个变量时遇到问题。

我尝试使用 dynamic 没有成功,我没有想法。

Entity1、Entity2 和 Entity3 具有完全相同的字段(从 Entity Framework 自动生成),但表不同。是否可以只使用一个变量来获得结果?

var repository1 = new RepositoryBase<Entity1>();
var repository2 = new RepositoryBase<Entity2>();
var repository3 = new RepositoryBase<Entity3>();

Enum RepositoryTypes
{
    Repo1 = 0,
    Repo2 = 1,
    Repo3 = 2
}

//Method Definition: RepositoryResolver(RepositoryTypes repoTypes);
var repository = RepositoryResolver(RepositoryTypes.Repo1); //Example. The RepositoryResolver should return one of the 3 RepositoryBase<EntityX>

var results = repository.Get(record => record.Name.Contains("fist name")).ToList();

foreach(var person in results)
{
    Console.WriteLine("First Name: {0}, Last Name: {1}", person.Name, person.LastName);
}

谢谢!

编辑

这是一个实体的例子:

Entity1 - Belongs to DataBase1
public string Name;
public string LastName;
public string Age;

Entity2 - Belongs to DataBase2
public string Name;
public string LastName;
public string Age;

Entity3 - Belongs to DataBase3
public string Name;
public string LastName;
public string Age;

【问题讨论】:

  • 实体有相同的列,它们也共享同一个表?
  • 什么意思,使用一个变量?您是指一个变量而不是 repository1, repository2, repository3,还是将所有 3 个存储库的结果存储在一个变量中?
  • 我的意思是使用一个变量来查询数据库var repository 然后var results = repository.Get(...) repository 变量将存储我传递给RepositoryResolver 的实体。不同的表是否具有相同的字段
  • 听起来您需要消除两个表并将某种 TypeId 的列添加到剩余的表中。如果所有列都相同,则应将它们全部存储在一起。

标签: c# linq generics reflection repository


【解决方案1】:

如果您有权访问 Entity1(以及 2 和 3)声明,请将它们基于一个抽象类或创建并让它们实现具有所述字段的接口。然后,您可以通过抽象基类或接口声明变量,瞧,您就在游戏中。类似于(在没有编译或智能感知的情况下写下我的头顶,所以可能会有错别字):

public interface IEntity
{
    string Name { get; set;}
    string LastName { get; set;}
}

public class Entity1 : IEntity
{
    public string Name { get; set;}
    public string LastName { get; set;}
}

public class Entity2 : IEntity
{
    public string Name { get; set;}
    public string LastName { get; set;}
}
//...and later in your main code...
foreach(IEntity person in results)
{
    Console.WriteLine("First Name: {0}, Last Name: {1}", person.Name, person.LastName);
}

【讨论】:

  • 感谢您的回复,但不幸的是我没有访问权限,因为它们是从实体框架自动生成的...所以即使我稍后更改它们也会再次更改(如果我运行自定义工具T4)
  • @CodeArtist 实体框架生成分部类,因此您可以创建实现接口的“伙伴”分部类定义。
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 2016-02-20
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多