从数据到模型的转换
本文关键字:转换 模型 数据 | 更新日期: 2023-09-27 18:15:11
我想将搜索到的数据转换为模型,因为它被分割了,因为我使用的是存储库模式。这是我的代码:
public List<Supplier> Find(string name)
{
using (var suppre = new SupplierRepository())
{
return suppre.Find(x => x.Supplier_Name == name).ToList().Select(x => new SupplierView()
{
Supplier_Id = x.Supplier_Id,
Supplier_Name = x.Supplier_Name,
Supplier_Address = x.Supplier_Address,
Email = x.Email,
Contact_No = x.Contact_No,
Contact_Person = x.Contact_Person,
Type_of_medicine = x.Type_of_medicine,
Product_ID = x.Product_ID
});
}
}
,它给了我一个错误:
不能将表达式类型
System.Collections.Generic.List<Dept.Model.SupplierModel>
转换为返回类型System.Collections.Generic.List<Dept.Data.Supplier>
您的方法签名期望返回
List<Supplier>
但是linq select的实际返回语句返回的是
List<SupplierView>
您可能只需要将返回类型更改为
List<SupplierView>
我赞赏您将数据模型与编辑模型分开使用。我建议使用像AutoMapper这样的工具来让这些工作变得更容易(和自动)。
使用automapper,你的方法看起来像这样:
public IEnumerable<SupplierView> Find(string name)
{
using (var suppre = new SupplierRepository())
{
return suppre
.Where(x => x.Supplier_Name == name)
.Select(x => AutoMapper.Mapper.Map<SupplierView>(x));
}
}
除了@mreyeros所说的,您还需要移动ToList
,因为Select
返回IEnumerable
。
public List<SupplierView> Find(string name)
{
using (var suppre = new SupplierRepository())
{
return suppre.Find(x => x.Supplier_Name == name).Select(x => new SupplierView()
{
Supplier_Id = x.Supplier_Id,
Supplier_Name = x.Supplier_Name,
Supplier_Address = x.Supplier_Address,
Email = x.Email,
Contact_No = x.Contact_No,
Contact_Person = x.Contact_Person,
Type_of_medicine = x.Type_of_medicine,
Product_ID = x.Product_ID
}).ToList();
}
}
你应该试试这个:
public List<SupplierView> Find(string name)
{
using (var suppre = new SupplierRepository())
{
return suppre.Find(x => x.Supplier_Name == name).Select(x => new SupplierView()
{
Supplier_Id = x.Supplier_Id,
Supplier_Name = x.Supplier_Name,
Supplier_Address = x.Supplier_Address,
Email = x.Email,
Contact_No = x.Contact_No,
Contact_Person = x.Contact_Person,
Type_of_medicine = x.Type_of_medicine,
Product_ID = x.Product_ID
}).ToList();
}
}
它给你一个错误的原因是因为你的方法签名声明你返回一个列表,这是你的数据,你首先要做选择,这是转换语句之前,你返回到列表