繁体   English   中英

如何解析通用存储库并在单个变量中使用它?

[英]How to resolve generic repository and use it in a single variable?

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

我尝试使用dynamic但没有成功,而且我没有主意。

Entity1Entity2Entity3具有完全相同的字段(从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;

如果您有权访问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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM