我有一个类似于以下结构的ViewModel
class Manager
{
string Name;
string Salary;
List<Employee> reportees;
void abstract SayHi();
}
class ShopManager() : Manager
{
public override void SayHi()
{
Console.WriteLine("Hey I am a ShopManager");
}
}
class GardenManager() : Manager
{
public override void SayHi()
{
Console.WriteLine("Hey I am a GardenManager");
}
}
我需要将Manager视图模型转换为实体。但实体可以是具体类型,如GardenManager或ShopManager(但具有与ManagerViewModel相同的属性)。
ShopManager可以将子项依赖为GardenManager,而Gardenmanager可以将子项依赖于其他具体类型。
如果ViewModel中的workType是“Shop”,则ViewModel应转换为ShopManager,同样也应转换为子项。
下面提到的示例实体。
NavigationView
有没有一种方法可以将这样的DTO转换为实体?
答案 0 :(得分:2)
不按建议使用AutoMapper,您可以在POCO类上使用隐式运算符或使用ExtensionMethods进行转换:
<强> TestProgram:强>
class Program
{
static void Main(string[] args)
{
ManagerViewModel viewModel = new ManagerViewModel
{
workType = "Garden"
};
// By implicit conversion
Manager manager1 = viewModel;
manager1.SayHi();
// By extension method
ShopManager manager2 = viewModel.ToEntity<ShopManager>();
manager2.SayHi();
Console.ReadLine();
}
}
<强>输出:强>
嘿,我是GardenManager
嘿,我是ShopManager
隐含操作员示例:
public class ManagerViewModel
{
public string Name;
public long salary;
public string workType;
public List<EmployeeViewModel> Dependents;
// User-defined conversion from ManagerViewModel to ShopManager or GardenManager
public static implicit operator Manager(ManagerViewModel viewModel)
{
switch (viewModel.workType)
{
case "Shop":
// TODO: Do your conversion, Build ShopManager based on ManagerViewModel
return new ShopManager();
case "Garden":
// TODO: Do your conversion, Build GardenManager based on ManagerViewModel
return new GardenManager();
default:
throw new NotImplementedException();
}
}
}
ExtensionMethod示例:
internal static class EntityExtensions
{
public static TSpecificManager ToEntity<TSpecificManager>(this ManagerViewModel managerViewModel)
where TSpecificManager : new()
{
// Do your conversion based on ManagerViewModel
return new TSpecificManager();
}
}
Extension Methods (C# Programming Guide)
希望有所帮助