简体   繁体   中英

Deep loading data with EF6 and LINQ

I am implementing an ASP.NET MVC 5 web app using ASP.NET Identity 2 and Troy Goode's PagedList . I need to display UserRole data in the following format in a JqGrid:


User Name | Role Name


This is my UserRole class:

public class UserRole : Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<int>
{
    [ForeignKey("UserId")]
    public virtual User User { get; set; }

    [ForeignKey("RoleId")]
    public virtual Role Role { get; set; }
}

This is my repository method

public virtual IQueryable<UserRole> GetAsQueryable(Expression<Func<UserRole, bool>> where)
    {
        return _dataContext.UserRoles.Where(where).AsQueryable();
    } 

This my Controller method (the GetAsPagedList method simply orders the input list, applies PagedList's .ToPagedList method to it and returns a subset of it):

        public ActionResult GridData(MvcJqGrid.GridSettings gridSettings)
        {
        IQueryable<UserRole> items = _repository.GetAsQueryable();

        IPagedList<T> pagedOrderedItems = PagingHelper<UserRole>.GetAsPagedList(
            items,
            gridSettings.SortOrder, gridSettings.SortColumn,
            gridSettings.PageIndex, gridSettings.PageSize);

        var jsonData = new
        {
            total = pagedOrderedItems.TotalItemCount / gridSettings.PageSize + 1,
            page = gridSettings.PageIndex,
            records = pagedOrderedItems.TotalItemCount,
            rows = (
                from c in pagedOrderedItems
                select new
                {
                    id = c.UserId + '-' + c.RoleId,
                    cell = new[]
                    {
                        "Edit",
                        "Details",
                        // TODO: something like this:
                        // [UserName] = c.User.UserName
                        // [RoleName] = c.Role.Name
                        c.Role.Name
                    }
                }).ToArray()
        };

        return Json(jsonData, JsonRequestBehavior.AllowGet);
    } 

I can'.t figure out where and how I should deep load data from the tables linked through foreign keys to my table (IE Users.UserName and Roles.Name) - could you please help?

_dataContext.UserRoles.Include("Role").Include("User").Where(where).AsQueryable();

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