Skip to main content
 首页 » 编程设计

c#之Linq 查询适用于 Web 应用程序,但在使用 NUnit 时会抛出错误

2024年01月29日24txw1958

我的服务有一个方法,它使用 Linq To Entities 选择如下数据:

  var test = _repository.DbSet(). 
            .Select(t => new CustomClass 
            { 
                Count = t.Count.ToString(), 
            }).ToList(); 

它适用于我的asp.net mvc 应用程序,但在通过Nunit 调用方法时抛出以下错误:

Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

请您参考如下方法:

我不确定您的代码在生产中如何工作,但根据 this link :

This exception mainly occurs when we query SQL database using entity framework. The problem is that you are calling ToString in a LINQ to Entities query (IQueryable to IEnumrable). That means the parser is trying to convert the ToString call into its equivalent SQL (which isn't possible...hence the exception).

您可以使用 .AsEnumerable() 或 .ToList() 修复它:

var test = _repository.DbSet(). 
        .AsEnumerable() 
        .Select(t => new CustomClass 
        { 
            Count = t.Count.ToString(), 
        }).ToList(); 

基于supported link你可以使用 SqlFunctions Class或 DbFunctions Class 无需全表扫描即可拥有此功能。