LINQ to Entities projections - asp.net-mvc-3

UPDATE: I essentially want to get a list of all permissions and a list of all permissions for a given role. I then want to mark each permission in a list of SelectListItems as selected when they already belong to the Role
I have three tables:
Project 1-* Role - Permission
I am trying to create and IEnumerable using projection that has all permissions in the list but when I project to SelectItemList it identifies the Permissions that are already associated with a particular role:
public IEnumerable GetAllPermissionsPLusRole(int projectid, int roleid)
{
using (var db = new Entities())
{
var permissions = (from p in db.Permissions
select p).ToList();
var permissionsForRole = from r in db.Roles
where r.RoleId == roleid && r.PrjectProjectId == contractid
select r.Permissions.ToList();
IEnumerable<SelectListItem> selectList = from p in permissions select new SelectListItem { Text = p.PermissionName, Value = p.PermissionId.ToString()};
return selectList;
}
}
What I want to do is have a conditional Selected in the projection so when I display the list I can show the permissions already associated to the Role.
Thanks in advance.

If I understand it right, you've already fetched all the data, now you just need to check if given permission is in the permissionsForRole list, i.e. like that:
IEnumerable<SelectListItem> selectList = from p in permissions
select new SelectListItem
{
Text = p.PermissionName,
Value = p.PermissionId.ToString(),
Selected = permissionsForRole.Contains(p)
};

Related

LINQ any compare to Guid List throw error

I am working on LINQ query in which I selecting all the claims against role. The role may or may not have claim so I did left join which is working fine as in following object claimList. Now I need to assign status object true or false based on if claim exist for a role which I am trying to use any but it throw error
error
cannot convert from system.Guid to system.Func<system.Guid, bool>
LINQ
var o2 = (from role in Context.Roles.Where(x=>x.Id == Guid.Parse("22000010-0002-4ADD-BC6F-7556616t66656"))
join roleClaimRef in Context.RoleClaims on role.Id equals roleClaimRef.RoleId into rc
select new
{
role,
roleClaim = rc.DefaultIfEmpty(),
claimList = (from claim in Context.Claims
select new
{
claim,
status = rc.Select(x=>x.ClaimId).Any(claim.Id) // throw error here....
})
}).ToList();
Where you say
status = rc.Select(x=>x.ClaimId).Any(claim.Id), you are passing Guid as a parameter into the Linq function Any, which requires a function that returns a boolean (See documentation from the Microsoft Docs).
I assume what you intend to do is select from rc where the ClaimId property is equal to your claim.Id.
In that case, do this:
status = rc.Select(x=>x.ClaimId).Any(claimId => claimId == claim.Id)
Hope this helps.
Your problem is because of using Guid.Parse in linq, you must create a variable and assign it, after that use the variable like below:
Guid tmpId = Guid.Parse("22000010-0002-4ADD-BC6F-7556616t66656");
var o2 = (from role in Context.Roles.Where(x=>x.Id == tmpId)
join roleClaimRef in Context.RoleClaims on role.Id equals roleClaimRef.RoleId into rc
select new
{
role,
roleClaim = rc.DefaultIfEmpty(),
claimList = (from claim in Context.Claims
select new
{
claim,
status = rc.Select(x=>x.ClaimId).Any(claim.Id)
})
}).ToList();
Check your ID using where condition
var o2 = (from role in Context.Roles.Where(x=>x.Id == Guid.Parse("22000010-0002-4ADD-BC6F-7556616t66656"))
join roleClaimRef in Context.RoleClaims on role.Id equals roleClaimRef.RoleId into rc
select new
{
role,
roleClaim = rc.DefaultIfEmpty(),
claimList = (from claim in Context.Claims
select new
{
claim,
status = rc.Where(a=>a.ClaimId==claim.Id).Select(x=>x.ClaimId)//check if claim id exist or not
})
}).ToList();

LINQ perform select and insert in single query

I am working on Entity Framework 6 in C# .NET CORE 2.0 application. I have requirement to get role id from database where roleName = x and add role reference to user as in one: many table
I want to avoid 2 trip to database, I want to do in one go or in single Linq query
UserDataModel userObj = new UserDataModel()
{
Id = fakeUserID,
Name = "k1",
Surname = "z",
Email = "k.z#yahoo.co.uk",
Roles = new List<UserRoleDataModel>
{
new UserRoleDataModel {
UserId = fakeUserID,
RoleId = Context.Roles.Where(roleName => roleName.Name == RoleName).Select(x=>x.Id)
}
}
};
Context.Add<UserModel>(userObj);
Context.SaveChanges();
above code gives me error at RoleId
refer in screen shot;
Error because you are assigning IQueryable to a Property of type Int (I Assumed its Int). You should do this:
RoleId = Context.Roles.Where(roleName => roleName.Name == RoleName && roleName.Id==Id).Select(x=>x.Id).First();

How do you filter a list based on matching items in another list?

I have an Organisation object
public class Organisation
{
OrgId {get....}
OrgName {get...}
AccountTypes { get....} //this is of type List<AccountType>
}
and an AccountType object
public class AccountType
{
AccountTypeId {get....}
AccountTypeName {get...}
}
I'm looking for a way to look through the existing Organisations List and remove AccountTypes from each organisation where the account types are not found in another list of AccountTypes (which would be a post back from a browser).
Would I do something like?
var foundOrgs = from org in orgs
where org.OrganisationId == Convert.ToInt32(hash["orgId"])
select org;
Organisation organisation = foundOrgs.ElementAt(0);
organisation.AccountTypes.Clear();
organisation.AccountTypes = // What goes here?
I'm looking to do a Linq query that will compare one list with another and return only those items where the AccountTypeIDs match, or are present.
You can use List<T>.RemoveAll:
// where accounts is IEnumerable<int>
organisation.AccountTypes.RemoveAll(at => !accounts.Contains(at.AccountTypeId));
EDITED CODE
//created account id list over here
var AccountTypeID = accountType.Select(x=>x. AccountTypeId);
//you code
var foundOrgs = from org in orgs
where org.OrganisationId == Convert.ToInt32(hash["orgId"])
select org;
Organisation organisation = foundOrgs.ElementAt(0);
organisation.AccountTypes.Clear();
//changes in code where you want to change -// What goes here?
List<AccountTypes> templist = organisation.AccountTypes;
organisation.AccountTypes =
from acc in templist
where !AccountTypeID.Conains(acc.AccountTypeId)
select acc).ToList();
EDIT
No sure but you can try out
var orgdata= from org in foundOrgs
select { OrgId =org.OrgId ,OrgName = org.OrgName ,
AccountTypes = ( from acc in org.AccountTypes
where !AccountTypeID.Conains(acc.AccountTypeId)
select acc) };
Try something like this
var ids = {1, 2, 3};
var query = from item in context.items
where !ids.Contains( item.id )
select item;
this will give you list of element which are not part of 1,2,3 i.e ids list , same you can apply in you code first find out which are not there and than remove it from the list
Image

Issue To Select/Show DropDown Selected Value At Edit() In Asp.net MVC 3

I Using Two Table User And Location In User Table I having LocationId And When I'm going to edit The User Form Then I need User With There Exact Location In Drop Down.but i didn't get that this is my code Of Controller:-
LogisticsEntities db = new LogisticsEntities();
RegisterModel Reg = new RegisterModel();
var tempUser = (from c in db.Users select new RegisterModel { _UserId = c.UserID, UserName = c.Name, Code = c.Code, Email = c.Email, Phone = c.Phone, JobRole = c.JobRole, StartDate = c.StartDate, EndDate = c.EndDate, LocationId = c.Location }).SingleOrDefault(x => x._UserId == id);
var varLocation = from Ls in db.Locations select Ls;
ViewData["LocationId"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
if (tempUser != null)
return View(tempUser);
else
return View();
And In My View I Have code: -
#Html.DropDownList("LocationID", (SelectList)ViewData["LocationId"])
Thanx In Advance..
You are using LocationID as both first parameter of the dropdown and inside ViewData. In order to generate a dropdown you need 2 things: the first argument will be used to generate the name attribute of the dropdown and used to bind the value back and the second argument must represent a collection of SelectListItem that will be used to create the options of the dropdown. So try using a different key for the collection:
ViewData["locations"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
and then:
#Html.DropDownList("LocationID", (SelectList)ViewData["locations"])

Filtering User table by MembershipUserCollection

So, I have ASP Membership set up in my application. I also have a separate User table for managing non-membership related data. During user management I need to make sure that my application queries both tables. I have the below Controller that returns a list of approved users, but it seems like there has to be a simpler way to accomplish this. What is a better way to do it?
QuoteExchangeDB _db = new QuoteExchangeDB();
[MyAuthorize(Roles = "Administrator")]
public ActionResult Admin()
{
MembershipUserCollection agents = Membership.GetAllUsers();
IEnumerable<MembershipUser> unfiltered = agents.Cast<MembershipUser>();
var filtered = unfiltered.Where(u => u.IsApproved);
List<User> users = new List<User>();
foreach (var item in filtered)
{
if (item.IsApproved)
{
Guid guid = (Guid)item.ProviderUserKey;
users.Add(_db.Users.Single(u => u.MembershipGuid.Equals(guid)));
}
}
return View(users);
}
This looks like you probably want a simple join in LINQ.
var filtered = Membership.GetAllUsers().Cast<MembershipUser>().Where(u => u.IsApproved);
var users = from f in filtered
join u in _db.Users on ((Guid)f.ProviderUserKey) equals u.MembershipGuid
select u;
You could probably make one statement out of that even:
var users = from f in Membership.GetAllUsers().Cast<MembershipUser>()
join u in _db.Users on ((Guid)f.ProviderUserKey) equals u.MembershipGuid
where f.IsApproved
select u;
Edit: Given that I'm not sure how joining an IEnumerable with an IQueryable might affect things/cause problems in this instance, here's a blog about doing that.

Resources