简体   繁体   English

使用select将Entity Framework实体映射到dto对象

[英]Mapping Entity Framework entity to dto object using select

I am using Entity Framework and I am trying to map using entities to a dto object using the following code but something is going wrong: 我正在使用Entity Framework,并且尝试使用以下代码将使用实体映射到dto对象,但出了点问题:

var fileUploads = _dbContext.FileUploads.Include("DocumentType").Include("Store");

if (jobSearchParams.DocumentTypeId != null)
{
    fileUploads = fileUploads.Where(x => x.DocumentTypeID == 6);
}

if (jobSearchParams.StoreId != null)
{
    fileUploads = fileUploads.Where(x => x.StoreID == jobSearchParams.StoreId);
}

if (!string.IsNullOrEmpty(jobSearchParams.Name))
{
    fileUploads = fileUploads.Where(d => d.Name.Contains(jobSearchParams.Name));
}

var dtos = Mapper.Map<IEnumerable<JobDocumentDto>>(documents);

var cnt = fileUploads.Count(); // 1412

var fileDocuments = fileUploads.AsEnumerable().Select(d => new JobDocumentDto
{
    DocumentID = d.ID,
    StoreID = d.StoreID,
    StoreName = d.Store.Name,
    Document = Mapper.Map<DocumentDto>(d),
    DocumentName = d.Name
}).ToList();

cnt  = fileDocuments.Count; // 0

With the AsEnumerable in the expression I have 0 objects after doing the select and if I remove the AsEnumerable I get the following error: 在表达式中使用AsEnumerable进行选择后,我有0个对象,如果删除了AsEnumerable ,则会出现以下错误:

System.NotSupportedException: LINQ to Entities does not recognize the method 'DataManagement.DTOs.DocumentDto MapDocumentDto' method, and this method cannot be translated into a store expression System.NotSupportedException:LINQ to Entities无法识别方法'DataManagement.DTOs.DocumentDto MapDocumentDto'方法,并且该方法无法转换为商店表达式

Add .ToList() before Select, so make it .ToList().Select(...)... . 在Select之前添加.ToList() ,使其成为.ToList().Select(...)...

Reason: LINQ is trying to convert the entire new JobDocumentDto {...} statement into query form, but it can't. 原因:LINQ试图将整个new JobDocumentDto {...}语句转换为查询形式,但是不能。 By running the query earlier this problem is avoided. 通过更早运行查询,可以避免此问题。

Also the AsEnumerable() may now be redundant, just try removing it. 而且, AsEnumerable()现在可能是多余的,只需尝试将其删除即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM