简体   繁体   中英

Accessing Included object

im working with a new ASP.NET MVC3 project and it seems like im missing something in my LINQ skills.

Im formatting data for a Json "call" to be used my a jqGrid.

It works fine but now i want to add a related object by a Linq .Include() expression. Think i better show with code.

var query = db.Products.Include("Category");

var jsonData = new
{
    total = 1,  // calc
    page = page,
    records = db.Products.Count(),
    rows = query.Select(x => new { x.Id, x.Name, x.PartNr })
        .ToList()
        .Select(x => new { 
            id = x.Id,
            cell = new string[] {
                x.Id.ToString(),
                x.Name.ToString(),
                x.PartNr.ToString(),
                //x.Category.Name.ToString() 
                //This does not work but object is there.
        }}).ToArray(),
    };

    return Json(jsonData, JsonRequestBehavior.AllowGet);

Problem area => //x.Category.Name.ToString() The strange thing here is if i Break and watch the query ( //x.Category.Name.ToString() ) i can actually find the attached Category object but how, if possible, can i use it in my ano method?

The problem is that you are first selecting an anonymous object with the properties Id, Name and PartNr. Then you execute this query against the database (with ToList()) and then you do a new select on the list of anonymous objects and try to access a property that's not in your anonymous object.

You should include the category in your anonymous object so you can access it in the second select. Or you should select the final structure with the first select query so it will be executed against your database.

This would work for example:

rows = query.Select(x => new { x.Id, x.Name, x.PartNr, x.Category })
                    .ToList()
                    .Select(x => new
                    {
                        id = x.Id,
                        cell = new string[] {
                        x.Id.ToString(),
                        x.Name.ToString(),
                        x.PartNr.ToString(),
                        x.Category.Name.ToString()
                        }
                    }).ToArray()

Or you simplify your query to only one and execute against the database:

 rows = query.Select(x => new
        {
            x.Id,
            cell = new string[]
            {
                x.Id.ToString(),
                x.Name.ToString(),
                x.PartNr.ToString(),
                x.Category.Name.ToString()
            }
        }).ToArray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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