我试图为具有相同列的表构建一些通用代码,但我在查明如何使用通用"解析器"为了只使用一个变量。
我试图使用dynamic
但没有成功,我没有想法。
Entity1
,Entity2
和Entity3
具有完全相同的字段(从实体框架自动生成),但有不同的表格。是否可以只使用一个变量来获得结果?
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;
答案 0 :(得分:0)
如果您可以访问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);
}