gpt4 book ai didi

c# - 将 EF DBquery 转换为 Viewmodel - 无法转换类型为“System.Data.Entity.Infrastructure.DbQuery”的对象

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:04 26 4
gpt4 key购买 nike

我有一个对结果进行分组的 Entity Framework 查询,我想将其传递给 View ,但我无法将其正确转换到 View 模型! (我想在 View 的网格中显示结果)

如果我使用这个类型转换

 viewModel.Groupeds = (IEnumerable<Grouped>) result;

我得到这些错误无法转换类型为“System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType4”的对象2[System.Nullable`1[System.Int32],System.Int32]]' 键入

我应该怎么投?

public ActionResult Show(int? id)
{
IEnumerable<dynamic> result = db.StatData
.GroupBy(k => new { k.QuestId, k.OptionId })
.Select(c => new
{
OptionId = c.Select(q => q.OptionId).FirstOrDefault(),
Counted = c.Select(q => q.id).Count(),
});

var viewModel = new StatsView();
viewModel.Groupeds = (IEnumerable<Grouped>) result;
return View(viewModel);
}

public class StatsView
{
public IEnumerable<Grouped> Groupeds { get; set; }
}


public partial class Grouped
{
public Nullable<int> Counted { get; set; }
public Nullable<int> OptionId { get; set; }
}

最佳答案

该代码创建了一个匿名类型的 IEnumerable,您应该创建 Grouped 结果的 IEnumerable。请注意,虽然您创建的匿名类型和 Grouped 具有相同的属性,但它们是不同的类型,不能相互转换。

public ActionResult Show(int? id)
{
//defining result as var is sufficient
var result = db.StatData
.GroupBy(k => new { k.QuestId, k.OptionId })
.Select(c => new Grouped//<<-here
{
OptionId = c.Select(q => q.OptionId).FirstOrDefault(),
Counted = c.Select(q => q.id).Count(),
}).ToList();//commit the query
var viewModel = new StatsView();
viewModel.Groupeds = result;//No need for casting
return View(viewModel);
}

最好在将查询发送到 View 之前提交查询(即通过 ToList()),因为如果上下文在 View 生成之前处理,则会导致错误。

关于c# - 将 EF DBquery 转换为 Viewmodel - 无法转换类型为“System.Data.Entity.Infrastructure.DbQuery”的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com