Linq with expect:在此上下文中仅支持原始类型或枚举类型

Linq with expect: Only primitive types or enumeration types are supported in this context

我有这个异常:无法创建类型为 ....ViewModels.Yarn.FilterNameDto 的常量值。此上下文仅支持基本类型或枚举类型。

视图模型:

public class YarnListViewModel
{
    public YarnListFilter YarnListFilter { get; set; }
    public IEnumerable<FilterNameDto> FilterNames { get; set; }
}

public class YarnListFilter
{
    public int? BrandId { get; set; }
    public string ProductName { get; set; }
}

public class FilterNameDto
{
    public string ProductName { get; set; }
}

在控制器中:

List<FilterNameDto> nlnames = new List<FilterNameDto>
{
    new FilterNameDto { ProductName = "Farouche" },
    new FilterNameDto { ProductName = "La Parisienne" },
...
};

var filternamesdb = _context.YarnFullAdmins
                    .Where(n => n.ProductName != null)
                    .GroupBy(n => n.ProductName)
                    .Select(n => n.FirstOrDefault());
if (yarnListFilter.BrandId > 0)
    filternamesdb = filternamesdb.Where(b => b.BrandId == yarnListFilter.BrandId);

// Until here everything works fine

var filternamesdblist = filternamesdb.Select(n => new FilterNameDto
    {
        ProductName = n.ProductName,
    }).Except(nlnames).ToList(); // I remove the names who are in the nlnames list

nlnames.AddRange(filternamesdblist); // And I add them so they come out first

var filternames = filternamesdblist;
if (yarnListFilter.BrandId == null || yarnListFilter.BrandId == 1)
    filternames = nlnames;

var viewModel = new YarnListViewModel
{
FilterNames = filternames
};

    return View(viewModel);

.Exept 是我的问题!

查看:

@Html.DropDownListFor(f => f.YarnListFilter.ProductName
, new SelectList(Model.FilterNames, "ProductName", "ProductName")
,"Filter by Name"
, new { @class = "form-control", @onchange = "this.form.submit();" })

我的目标是让一些实际在查询结果中(在这个列表中的任何地方)的项目(在 nlnames 列表中引用)首先出现。所以,我想我将它们从列表中删除,然后添加它们,以便它们首先被列出。 或者是否有(我确定有)更好的方法来实现这一点?!?!?

为了清晰而简短地恢复它: 数据库 returns Aaa, Bbb, Ccc, Ddd, Eee 我希望 Bbb、Ddd 成为第一位! 预先感谢您的帮助。

问题是您的对象 nlnames 无法翻译成 SQL 服务器可以理解的东西。为了解决这个问题,您可以在 .Except()

之前调用 .ToList()
var filternamesdblist = filternamesdb
    .Select(n => new FilterNameDto
    {
        ProductName = n.ProductName,
    })
    .ToList()
    .Where(n => !nlnames.Any(nl => nl.ProductName == n.ProductName))
    .ToList();

或者,您可以将 nlnames 的类型更改为 List<string>,这可以被 SQL 服务器理解:

var nlnames = new List<string> { "Farouche", "La Parisienne" };

var filternamesdblist = filternamesdb
    .Where(n => !nlnames.Contains(n.ProductName))
    .Select(n => new FilterNameDto
    {
        ProductName = n.ProductName,
    })
    .ToList();