c# - 如果不调试,Linq to Entity Framework 返回值会导致错误

标签 c# entity-framework linq

我正在尝试在带有 gridview 的 WPF 应用程序上以代码优先的方式使用 Entity Framework 6.1.3 来显示一些数据。但是,当我尝试查询数据库时,返回结果时部分数据丢失了。

我有以下模型类:

public class Categoria
{
    [Key]
    public Guid IDCategoria { get; set; }
    public string Nombre { get; set; }
    public bool Visible { get; set; }
    public virtual List<SubCategoria> SubCategorias { get; set; }
}

public class SubCategoria
{
    [Key]
    public Guid IDSubCategoria { get; set; }
    public string Nombre { get; set; }
    public Categoria IDCategoria { get; set; }
    public bool Visible { get; set; }
}

dbContext:

public class PresupuestoContext : DbContext 
{
    public DbSet<SubCategoria> SubCategorias { get; set; }
    public DbSet<Categoria> Categorias { get; set; }

    public PresupuestoContext() 
    {
        var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
    }

为了查询数据,我使用了以下函数:

public static IEnumerable<Categoria> GetCategories()
{
    using (var db = new PresupuestoContext())
    {
        var query = (from b in db.Categorias
                    orderby b.Nombre
                    select b).ToList();
        return query;
    }
}

这里的结果会返回两次,直到到达这段代码上的 GUI:

private void button_Click(object sender, RoutedEventArgs e)
{
    var resultado = Information.GetCategories();
    dataGrid.ItemsSource = resultado.ToList();
}

并且数据显示在网格上

expected result

但是,只有当我在 GetCategories() 方法上设置断点并查看对象时它才有效

observed debugger

如果我不这样做,SubCategorias 列表会抛出一个错误

enter image description here

错误:

((System.Data.Entity.DynamicProxies.Categoria_DEF110A52595D71D72012731564BC6530201A7738FF55979B05BFABCE100FD94)new System.Collections.Generic.Mscorlib_CollectionDebugView(resultado).Items1).SubCategorias

error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'

我得到以下结果

enter image description here

我怎样才能在不进入调试器的情况下得到正确的结果?

知道为什么会这样吗?

最佳答案

你必须这样做。

注意:使用带有 Include 的预先加载。

using System.Data.Entity;

public static IEnumerable<Categoria> GetCategories()
{
    using (var db = new PresupuestoContext())
    {
        var query = (from b in db.Categorias
                    orderby b.Nombre
                    select b)
                    .Include(p => p.SubCategorias)
                    .ToList();

        return query;
    }
} 

关于c# - 如果不调试,Linq to Entity Framework 返回值会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39865298/

相关文章:

c# - 使用 Linq to XML 删除父元素

c# - 亚音速 3.0 : How to use LIKE on objects?

c# - 似乎无法将 Linq 与 ASP.Net 导航菜单一起使用

c# - Url.Action 不适用于使用路由注释在 Controller 中指定的路由

c# - 如何强制 EF 使用连接而不是拆分复杂的查询?

c# - Entity Framework .find(id) NullReferenceException

C# webapi 异步上下文问题

c# - 在 WPF 中将事件从样式传播到 MainWindow

c# - Entity Framework 运行时连接字符串

c# - 在 .NET 中创建加密安全随机 GUID