Maske
Maske

Reputation: 864

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.

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();

Upvotes: 3

Views: 209

Answers (2)

Maske
Maske

Reputation: 864

I changed

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

for

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

Upvotes: 0

puddinman13
puddinman13

Reputation: 1408

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. 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. 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.

More on include method... MSDN Explanation of Include Method

Upvotes: 1

Related Questions