将 table int id 存储到 ViewModel class 的 int[] 属性中

Store table int ids into an int[] attribute of a ViewModel class

我想从联合 table 的列中提取所有 int ID,并将其存储在 ViewModel class.

的属性中

注意:CategorisationFooBar 实体 class 的映射 table。在这种情况下,我只过滤 IdFoo

var model = _ctx.FooDbSet.Where(y => y.Id == x.Id).Select(x => new FooManageVM
        {
            // ... other attributes here

            CategorisationIds = _ctx.CategorisationDbSet.Where(w => w.Foo.Id == id).Select(s => s.Foo.Id).ToArray()

        }).Single();

尽管最后有 .ToArray() 方法(.ToArray<int>() 也不起作用),但我收到此错误:

LINQ to Entities does not recognize the method 'Int32[] ToArray[Int32](System.Collections.Generic.IEnumerable`1[System.Int32])' method, and this method cannot be translated into a store expression.

我尝试将查询提取到上面,例如:

var ids = _ctx.CategorisationDbSet.Where(w => w.Foo.Id == id).Select(s => s.Foo.Id);

然后在下面:

// this is of type int[]
CategorisationIds = ids.ToArray()

但这也没有用。

首先使用 ToList():

.Select(s => s.Foo.Id).ToList().ToArray()

当您使用 ToList 时,从数据库中获取记录并准备好作为 linq 对象。

我认为最简单的方法是将 CategorisationsIds 的类型更改为 IEnumerable<int>

此外,请检查您是否引用了 System.Linq

但如果这不起作用,您可以查询匿名对象并使用 .Single():

的结果实例化 FooManageVM
var result = _ctx.FooDbSet.Where(y => y.Id == x.Id).Select(x => 
    {
        // ... other attributes here

        CategorisationIds = _ctx.CategorisationDbSet.Where(w => w.Foo.Id == id).Select(s => s.Foo.Id)

    }).Single();

var model = new FooManageVM {
     // ... other attributes here
     CategorisationIds = result.CategorisationIds.ToArray();
}

.ToArray() 调用移到主查询之外

尝试:

var ids = _ctx.CategorisationDbSet.Where(w => w.Foo.Id == id).Select(s => s.Foo.Id).ToArray();

然后:

CategorisationIds = ids;