C# 将表int id存储到ViewModel类的int[]属性中
我想从联合表的列中提取所有C# 将表int id存储到ViewModel类的int[]属性中,c#,asp.net-mvc,entity-framework,linq-to-entities,C#,Asp.net Mvc,Entity Framework,Linq To Entities,我想从联合表的列中提取所有intid,并将其存储在ViewModel类的属性中 注:categorization是Foo和Bar实体类的映射表。在这种情况下,我只过滤Foo的Ids var model = _ctx.FooDbSet.Where(y => y.Id == x.Id).Select(x => new FooManageVM { // ... other attributes here Categorisa
int
id,并将其存储在ViewModel类的属性中
注:categorization
是Foo
和Bar
实体类的映射表。在这种情况下,我只过滤Foo
的Id
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()
也不起作用),但我得到了以下错误:
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将从DB获取的记录作为linq对象列出时。我认为最简单的方法是将CategorizationId的类型更改为
IEnumerable
另外,检查您是否参考了System.Linq
但如果这不起作用,您可以查询匿名对象并使用.Single()的结果实例化FooManageVM:
将.ToArray()
调用移到主查询之外
尝试:
然后:
刚刚测试过-恐怕此更改没有任何作用。@developer10错误是什么?您确定DB上有值吗?我猜您使用的是旧版本的EF(<6?)。我不确定您是否需要.ToArray()调用。您在没有使用它的情况下尝试过吗?现在错误是:
无法在查询结果中初始化数组类型“System.Int32[]”。考虑使用Stase.Copyth.GrimiC.List.1(St.Int32)。< /代码> OK,你有没有尝试过这个建议?不要使用.ToArray()
而使用.ToList()
变量Id=\u ctx.CategorisationDbSet.Where(w=>w.Foo.Id==Id)。选择(s=>s.Foo.Id).ToList()
我使用这个属性来存储多个selectlist
所选项目,所以如果它是IEnumerable,我想我必须坚持使用int[]
类型。然后,当绑定到控件时,只需调用.ToArray()。它可以工作(我删除了前面的注释-我的代码中有一个严重的缺陷,它提取了Foo id,而不是select list的Bar id)
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();
}
var ids = _ctx.CategorisationDbSet.Where(w => w.Foo.Id == id).Select(s => s.Foo.Id).ToArray();
CategorisationIds = ids;