我使用以下代码来避免重复:
private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
{
return x => new IncidentVM
{
incident_ID = x.incident_id,
incident_description = x.incident_description,
file_names = x.file_names,
location = x.location,
Actions =
x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
{
incident_ID = z.incident_id,
action_ID = z.action_id,
action_description = z.action_description
})
//actionList = new List<ActionVM>(d => mappingActionVM)
};
}
然后我可以做以下事情:
List<IncidentVM> incidents = db.Incident_Log.Select(mappingIncidentVM).ToList();
它将Incident_Log实体映射到我的viewModel IncidentVM。 我的问题是,我希望我可以直接映射到列表而不是IEnumerable.Something像这样:
private static Expression<Func<Incident_Log, IncidentVM>> mappingIncidentVM()
{
return x => new IncidentVM
{
incident_ID = x.incident_id,
incident_description = x.incident_description,
file_names = x.file_names,
location = x.location,
actionList =
x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
{
incident_ID = z.incident_id,
action_ID = z.action_id,
action_description = z.action_description
}).ToList()
};
}
但这是一个错误:
LINQ to Entities does not recognize the method System.Collections.Generic.List[ViewModel.ActionVM] ToList[ActionVM](System.Collections.Generic.IEnumerable([ViewModel.ActionVM]) method, and this method cannot be translated into a store expression.
无法识别ToList()。
这是我的ViewModel:
public class IncidentVM
{
public int incident_ID { set; get; }
[Display(Name = "Description*")]
[Required]
public string incident_description { get; set; }
[Display(Name = "Specific Location*")]
[Required]
public string location { set; get; }
public string file_names { set; get; }
//Here is the problem, I 'd like to have only actionList
public IEnumerable<ActionVM> Actions { get; set; }
public List<ActionVM> actionList { get; set; }
这是Action_Log对象的模型:
public partial class Action_Log
{
public int action_id { get; set; }
public int incident_id { get; set; }
public string action_description { get; set; }
public virtual Incident_Log Incident_Log { get; set; }
}
在这种情况下是否可以直接映射到List?
答案 0 :(得分:2)
问题是LINQ无法翻译ToList
所以只需要IEnumerable
,然后在处理本地数据时使用ToList
(执行查询后),你应该细
答案 1 :(得分:-1)
尝试
actionList =
x.Action_Log.Where(y => y.assigned_to == y.assigned_to).Select(z => new ActionVM
{
incident_ID = z.incident_id,
action_ID = z.action_id,
action_description = z.action_description
}).ToList<ActionVM>()