我尝试使用ValueInjecter将多个对象映射到视图模型对象。但是它没有按我预期的那样工作。
码:
class Call
{
public string Number { get; set; }
public string CustomerNumber { get; set; }
}
class Operation
{
public int ID { get; set; }
public string CallNumber { get; set; }
public string TimeFrom { get; set; }
}
class Customer
{
public string Number { get; set; }
public string Name { get; set; }
}
class CallViewModel
{
public string Number { get; set; }
public string CustomerName { get; set; }
public string OperationTimeFrom { get; set; }
}
class Test
{
static void Main(string[] args)
{
var call = new Call { Number = "001337", CustomerNumber = "000001" };
var op = new Operation { ID = 1, CallNumber = "001337", TimeFrom = "08:00" };
var customer = new Customer { Number = "000001", Name = "John Doe" };
var viewModel = new CallViewModel();
viewModel.InjectFrom(call, op, customer);
Console.WriteLine("Number:\t\t\t" + viewModel.Number);
Console.WriteLine("CustomerName:\t\t" + viewModel.CustomerName);
Console.WriteLine("OperationTimeFrom:\t" + viewModel.OperationTimeFrom);
Console.ReadLine();
}
}
预期产量:
Number: 001337
CustomerName: John Doe
OperationTimeFrom: 08:00
有效输出:
Number: 00001
CustomerName:
OperationTimeFrom:
注意
在
Call.Number
中表示为Number
的CallViewModel
被Customer.Number
覆盖。 CustomerName
和OperationTimeFrom
都不会获得其指定源Customer.Name
和Operation.TimeFrom
的值。在那种情况下我该怎么办? ValueInjecter甚至支持这种情况吗?
最佳答案
我想你想过用另一种方式展平
它的运作方式是
obj.Prop.Prop1.Prop2 to obj.PropProp1Prop2
这是您的代码修改:
using System;
using Omu.ValueInjecter;
namespace ConsoleApplication1
{
class Program
{
private static void Main(string[] args)
{
var call = new Call { Number = "001337", CustomerNumber = "000001" };
var op = new Operation { ID = 1, CallNumber = "001337", TimeFrom = "08:00" };
var customer = new Customer { Number = "000001", Name = "John Doe" };
var model = new
{
Call = call,
Customer = customer,
Operation = op
};
var viewModel = new CallViewModel();
viewModel.InjectFrom<FlatLoopValueInjection>(model);
Console.WriteLine("Number:\t\t\t" + viewModel.CallNumber);
Console.WriteLine("CustomerName:\t\t" + viewModel.CustomerName);
Console.WriteLine("OperationTimeFrom:\t" + viewModel.OperationTimeFrom);
Console.ReadLine();
}
class Call
{
public string Number { get; set; }
public string CustomerNumber { get; set; }
}
class Operation
{
public int ID { get; set; }
public string CallNumber { get; set; }
public string TimeFrom { get; set; }
}
class Customer
{
public string Number { get; set; }
public string Name { get; set; }
}
class CallViewModel
{
public string CallNumber { get; set; }
public string CustomerName { get; set; }
public string OperationTimeFrom { get; set; }
}
}
}
关于c# - 使用ValueInjecter展平,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13740338/