MVC LINQ to Entities 无法识别方法调用函数 - 何时调用函数?

MVC LINQ to Entities does not recognize the method call function - when to call function?

我试图在 LINQ 语句中调用一个函数,显然不能将其转换为 SQL。这是我的代码,我正在尝试将日期时间转换为周数。最好的方法是什么,我是否循环遍历数据并更新 ViewModel?

控制器

public ActionResult Listings(string categoryName)
{
    HomeServices service = new HomeServices();

    return View(service.GetListingsViewModel(categoryName);
}

查看模型

public class ResultsViewModel
{
    public System.Guid AdGuid { get; set; }
    public Nullable<System.DateTime> ListDate { get; set; }
    public string ListingAge { get; set; }
    public string Image1 { get; set; }

}
public class ListingsViewModel
{
    public IEnumerable<ResultsViewModel> ResultsVM { get; set; }
    public int TotalCount { get; set; }
}

服务

internal ListingsViewModel GetListingsViewModel(string categoryName)
{
    var listings = GetListingsVM(categoryName);
    var totalCount = listings.Count();

    return new ListingsViewModel()
    {
        ListingResultsVM = listings,
        TotalCount = totalCount
    };
}

internal IEnumerable<ResultsViewModel> GetListingsVM(string categoryName)
{
    var listings = Listings
      .Where(x => x.Category == categoryName)
      .Select(x => new ResultsViewModel
    {
        AdGuid = x.AdGuid,
        ListDate = x.ListDate,
        ListingAge = Logic.App.GetListingAge(x.BirthDate ?? DateTime.Now),
        Image1 = x.ListingImage.Image1
    });

    return listings;
}

Logic.App

public static string GetListingAge(System.DateTime varListDate)
{
    //Function code to convert DateTime to Weeks
    return functionReturnValue;
}

首先,下载所需数据。然后,在本地将其操作为需求。

var listings = Listings
  .Where(x => x.Category == categoryName)
  .Select(x => new 
  {
    AdGuid = x.AdGuid,
    ListDate = x.ListDate,
    Image1 = x.ListingImage.Image1
  })
  .AsEnumerable() // make call to DB
  .Select(x => new ResultsViewModel
  {
    AdGuid = x.AdGuid,
    ListDate = x.ListDate,
    ListingAge = Logic.App.GetListingAge(x.BirthDate ?? DateTime.Now),
    Image1 = x.Image1
  })
  .ToList();  //Materialize the local query into a real list.

我强烈建议您在这些电话结束时总是 .ToList()。否则多次调用此方法将 return 完全不同 ResultsViewModel.

列表

What can happen if you return an IQueryable as an IEnumerable.

I am trying to call a method that obviously can't be called in SQL.

你确定吗?使用最新版本的 SQL,您可以告诉 EF 调用数据库中的用户定义函数,而不是调用 C# 函数调用。

您想用 DbFunction 注释函数。