C# 将IEnumerable模型映射到视图
保持这个基本,我有两个模型。客户和客户服务模型。我想将属性映射到另一个属性C# 将IEnumerable模型映射到视图,c#,asp.net-mvc,automapper,C#,Asp.net Mvc,Automapper,保持这个基本,我有两个模型。客户和客户服务模型。我想将属性映射到另一个属性 public class Customer { public string CompanyName { get; set; } public int CustomerType { get; set; } public IEnumerable<ContactViewModel> CustomerContacts { get; set; } } public class Customer
public class Customer
{
public string CompanyName { get; set; }
public int CustomerType { get; set; }
public IEnumerable<ContactViewModel> CustomerContacts { get; set; }
}
public class CustomerViewModel
{
public string CompanyName { get; set; }
public int CustomerType { get; set; }
public ContactName {get;set;}
public ContactTel {get;set;}
}
尝试使用linq
public ActionResult Index()
{
var viewmodel = CustomerViewModel();
return View(viewmodel);
}
private static CustomerViewModel ()
{
return new CustomerViewModel
{
...
ContactName = BusinessLogic.GetContactName("Microsoft");
ContactTel = BusinessLogic.GetContactTel();
}
}
其中BusinessLogic是您的“大脑”——决定从数据中获取什么的类,并使用linq获取电话和姓名:
public static class BusinessLogic
{
public static string GetContactName(string companyName)
{
var c = new Customer () ... // get you Customer-object
var q = (from contacts in c.CustomerContacts
where contacts.CompanyName == companyName
select contacts.ContactName).First();
return q;
}
}
但我可以看出你有一个错误。您混淆了视图模型数据(希望在网页上为用户显示)和数据模型(显示对象模型“联系人”)。换句话说。。最好使用特殊的模型类作为CustomerContacts的类型。对不起,我的英语很好。希望我帮了你。我不确定用AutoMapper是否可以做到这一点。您可以尝试定义扩展方法,例如:
public static CustomerViewModel ToViewModel(this Customer cust)
{
return new CustomerViewModel()
{
CompanyName = cust.CompanyName,
CustomerType = cust.CustomerType,
ContactName = cust.CustomerContacts.First().ContactName,
ContactTel = cust.CustomerContacts.First().ContactTel
};
}
当然,在上面加一点验证会很好。
然后你就这样使用它:
Customer cust= GetCustomer();
CustomerViewModel model= cust.ToViewModel();
如果
CustomerContacts
为null
或为空(我将尝试提出一个更可靠的解决方案),这将引发异常,但以下是一些对愉快路径有效的方法:
Mapper.CreateMap<Customer, CustomerViewModel>()
.ForMember(dest => dest.ContactName, opt => opt.MapFrom(src => src.CustomerContacts.First().ContactName))
.ForMember(dest => dest.ContactTel, opt => opt.MapFrom(src => src.CustomerContacts.First().ContactTel));
您想在映射过程中进行筛选,或者您知道它在映射之前只有一条记录吗?我知道它将只保存一条记录。@JamesAndrewSmith,Linq似乎是一条出路,您必须使用automapper吗?
Mapper.CreateMap<Customer, CustomerViewModel>()
.ForMember(dest => dest.ContactName, opt => opt.MapFrom(src => src.CustomerContacts.First().ContactName))
.ForMember(dest => dest.ContactTel, opt => opt.MapFrom(src => src.CustomerContacts.First().ContactTel));
public class Customer
{
/* other members */
public string ContactName
{
get
{
string name = null;
if (CustomerContacts != null && CustomerContacts.Any())
{
name = CustomerContacts.First().ContactName;
}
return name;
}
}
public string ContactTel
{
get
{
string tel = null;
if (CustomerContacts != null && CustomerContacts.Any())
{
tel = CustomerContacts.First().ContactTel;
}
return tel;
}
}
}