我希望将搜索到的数据转换为模型,因为我已经拆分,因为我使用的是存储库模式。 这是我的代码:
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>
答案 0 :(得分:2)
您的方法签名期望返回
List<Supplier>
但你的linq select中的实际return语句返回
List<SupplierView>
您可能只需要将返回类型更改为
List<SupplierView>
答案 1 :(得分:0)
我赞赏您使用编辑模型中的单独数据模型。我建议使用像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));
}
}
答案 2 :(得分:0)
除了@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();
}
}
答案 3 :(得分:0)
你应该试试这个:
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();
}
}
它给你一个错误的原因是因为你的方法签名声明你返回一个List,这是你的数据,你首先要做的是选择哪个是转换语句,然后再将它返回列表。