lbrahim
lbrahim

Reputation: 3810

Using EF to return specific formatted JSON from ASP.NET MVC

I have a model like below where PermissionGroup has 1-Many relationship with Permission and Permission and Roles have Many-Many relationship.

PermissionGroup 1-----* Permission *--------* Role

I have to be able to return JSON in the following format:

PermissionGroupId : 1,
PermissionGroupName : "Market",
Permissions : [
 {PermissionId : 1, PermissionName : "Create"},
 {PermissionId : 2, PermissionName : "Update"}
]

That will be asked for a specific RoleId.

Problem:

Since, PermissionGroup has no relation directly with Role so I cannot do a Where linq query. I could do the following but it is not returning desired result like above.

public JsonResult GetRolePermission(int roleid)
{
    var list = con.PermissionGroups.Select(pg => new
    {
        PermissionGroupId = pg.PermissionGroupId,
        PermissionGroupName = pg.PermissionGroupName,
        Permissions = pg.Permissons.Select(pe => new
        {
            PermissionId = pe.PermissionId,
            PermissionName = pe.PermissionName
        }) 
    })//Maybe do the where query here somehow like where(f => f.RoleId == roleid);

    return Json(list);
}

Any suggestion is appreciated.

Upvotes: 0

Views: 330

Answers (2)

Tony
Tony

Reputation: 7445

You can use Any method in Where? Like this:

var list = con.PermissionGroups
    .Where(pg => pg.Permissons.Any(p => p.Roles.Any(r => r.RoleId == roleId)))
    .Select(pg => new
    {
        PermissionGroupId = pg.PermissionGroupId,
        PermissionGroupName = pg.PermissionGroupName,
        Permissions = pg.Permissons.Select(pe => new
        {
            PermissionId = pe.PermissionId,
            PermissionName = pe.PermissionName
        })
    });

Upvotes: 2

lbrahim
lbrahim

Reputation: 3810

I found a way to do this but highly doubt that it is efficient.

var getPermissionsForRole = context.Roles.Where(roleid => roleid.RoleId == 1).Select(p => p.Permissions).ToList();
var getAllPermissionGroup = context.PermissionGroups.ToList();

List<PermissionGroup> jsonPg = new List<PermissionGroup>();

foreach (var pg in getAllPermissionGroup)
{
    PermissionGroup newPg = new PermissionGroup();
    newPg.PermissionGroupId = pg.PermissionGroupId;
    newPg.PermissionGroupName = pg.PermissionGroupName;
    newPg.Permissons = new List<Permission>();

    foreach (var pers in getPermissionsForRole[0])
    {
        if (pers.PermissionGroup.PermissionGroupId == pg.PermissionGroupId)
        {
            Permission newPe = new Permission();
            newPe.PermissionId = pers.PermissionId;
            newPe.PermissionName = pers.PermissionName;

            newPg.Permissons.Add(newPe);
        }
    }

    if (newPg.Permissons.Count > 0)
    {
        jsonPg.Add(newPg); 
    }
}

var json = JsonConvert.SerializeObject(jsonPg);

Still open to better code.

Upvotes: 0

Related Questions