我正在尝试在带有 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();
}
并且数据显示在网格上
但是,只有当我在 GetCategories()
方法上设置断点并查看对象时它才有效
如果我不这样做,SubCategorias
列表会抛出一个错误
错误:
((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'
我得到以下结果
我怎样才能在不进入调试器的情况下得到正确的结果?
知道为什么会这样吗?
最佳答案
你必须这样做。
注意:使用带有 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/