存储表INT ID进入ViewModel类的int []属性



我想从关节表的列中拉出所有int ID,并将其存储在ViewModel类的属性中。

注意:CategorisationFooBar实体类的映射表。在这种情况下,我仅过滤FooId s。

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()

但这也不起作用。

我认为最简单的事情是将分类的类型更改为 IEnumerable<int>

另外,请检查您参考系统。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;

首先使用tolist((:

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

当您使用Tolist时

最新更新