简体   繁体   English

获取泛型类型的ICollection属性

[英]Get ICollection property of generic type

I'm new in ASP.NET MVC 5, I need get the Icollection property and search into other property, if printed the result of the first search is fine, but when i go to search in the result is null. 我是ASP.NET MVC 5的新手,我需要获取Icollection属性并搜索到其他属性,如果打印第一次搜索的结果很好,但是当我去搜索结果时为null。

what is the problem? 问题是什么?

var userId = User.Identity.GetUserId();
var user = db.Users.Include( u=> u.Sucursales)
                   .Where(u => u.Id == userId)
                   .SingleOrDefault();

if( user != null )
{
    var sucursal = user.Sucursales.Include(s => s.Emisor)
                                  .Where(s => s.ID == suc)
                                  .SingleOrDefault();
    if (sucursal != null)
    {
        var tipoCfe = sucursal.Emisor.TiposCfe
                                     .Where(t => t.ID == factura)
                                     .SingleOrDefault();

Your query will take place right away since you are using SingleOrDefault() , see this StackOverflow question pertaining to SingleOrDefault() Your Include(s => s.Emisor) sticks out to me though. 您的查询将立即发生,因为您正在使用SingleOrDefault() ,请参阅此有关SingleOrDefault()的StackOverflow问题。您的Include(s => s.Emisor)虽然适用于我。 Since Emisor wasn't included when fetching the user, you will not be able to request that since your query is no longer of type IQueryable. 由于在获取用户时未包含Emisor,因此您将无法请求,因为您的查询不再是IQueryable类型。 Your query has already been executed. 您的查询已被执行。

In order to retrieve the data you require, you will have to obtain the data during your first query. 为了检索您需要的数据,您必须在第一次查询期间获取数据。 I would do something similar to: db.Users.Include("Sucursales.Emisor") when you retrieve the user. 当你检索用户时,我会做类似的事情: db.Users.Include("Sucursales.Emisor")

More on include method... MSDN Explanation of Include Method 更多关于include方法... MSDN包含方法的解释

I changed 我变了

var user = db.Users.Include( u=> u.Sucursales)

for 对于

var user = db.Users.Include("Sucursales.Emisor") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM