Filtering User table by MembershipUserCollection - asp.net-mvc-3

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.

Related

Linq - Add multiple "dynamic" conditions

Problem
I have an IQueryable, and I want to search it based on roles. An user can have multiple roles so I want to be able to add multiple search conditions (one on top of another).
public void OnGet()
{
var productionUnits = _context.ProductionUnits;
IQueryable query = productionUnits;
if (User.IsInRole(CustomRole.AdministratorUAP1))
{
query = productionUnits.Where(c => c.Id == (int)ProductionUnitEnum.UAP1);
}
if (User.IsInRole(CustomRole.AdministratorUAP2))
{
query = productionUnits.Where(c => c.Id == (int)ProductionUnitEnum.UAP2);
}
...
}
Expected Output
If the user is in multiple roles, for example UAP1 and UAP2, I want the query to get both of them in the Where clause. Is there any way to achieve this (I know I could do List.AddRange(), but I really want to update the query instead). Is there any way to achieve this?
I would creeate a list of roles for the user and use Contains in the query:
var roleIds = new List<int>();
if (User.IsInRole(CustomRole.AdministratorUAP1))
{
roleIds.Add(ProductionUnitEnum.UAP1);
}
if (User.IsInRole(CustomRole.AdministratorUAP2))
{
roleIds.Add(ProductionUnitEnum.UAP2)
}
var query = productionUnits.Where(c => roleIds.Contains(c.Id));
That will add an IN clause to your query for those two roles. If you have more than two roles just add them to the list as appropriate.
Each Linq function returns an IQueryable<>, so just keep reusing that:
IQueryable<T> query = productionUnits; // note the <T>
if (User.IsInRole(CustomRole.AdministratorUAP1))
query = query.Where(c => c.Id == (int)ProductionUnitEnum.UAP1);
if (User.IsInRole(CustomRole.AdministratorUAP2))
query = query.Where(c => c.Id == (int)ProductionUnitEnum.UAP2);
If the user is in multiple roles, for example UAP1 and UAP2
Then your database is fundamentally broken, you're checking those values against a single field: c.Id. One number can't be both values at the same time.

CRM Linq find all parents that have 0 children

How can I find (preferably using CRM Linq) parent entities that have 0 children. For example how can I find all accounts that have 0 contacts.
If you are going to use the query expression route, which I would recommend then the following code will be useful
var entityAlias = "con";
var query = new QueryExpression
{
EntityName = "account",
ColumnSet = new ColumnSet(true),
Criteria =
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression(entityAlias, "contactid",ConditionOperator.Null)
}
}
LinkEntities =
{
new LinkEntity
{
EntityAlias = entityAlias,
LinkFromEntityName = "account",
LinkFromAttributeName = "accountid",
LinkToEntityName = "contact",
LinkToAttributeName = "parentcustomerid",
Columns = new ColumnSet("parentcustomerid", "contactid"),
JoinOperator = JoinOperator.LeftOuter,
}
},
};
var response = service.RetrieveMultiple(query);
var accounts = response.Entities;
In this code I have not limited the columns, this will reduce performance and you should only return the columns needed.
If there is the case for more than 5000 records are going to be returned then you will need to use paging and loop the query to find all the entities,
This can be found here:
https://msdn.microsoft.com/en-us/library/gg327917.aspx
However if you are certain you want to use LINQ then you can use the following code:
public static IEnumerable<Account> FindAccountsWithNoContacts()
{
var contactRelationship = new Relationship("contact_customer_accounts");
foreach(var account in XrmContext.AccountSet)
{
XrmContext.LoadProperty(contactRelationship);
if(!account.RelatedEntities.ContainsKey(contactRelationship)
yield return account;
}
}
My problem with the LINQ code is that all the enities, both the account and contact entities, will be loaded into memory. With large entity sets this can cause OutOfMemoryException, whereas the query expression route will pass the query to the Dynamics server to execute; which should make the execution of the code faster.
The thing you are looking for is left outer join. Which is unfortunately not possible in CRM using LINQ. However you can do it using query expression or FetchXML.
Here is a link that can help you:
https://community.dynamics.com/crm/b/gonzaloruiz/archive/2014/02/23/all-about-outer-join-queries-in-crm-2011-and-crm-2013

Linq Query for Complex Object

Everyone - I have the following set of objects:
User { String:Name, List<Devices> }
Device {String:Name, DeviceVariationInfo }
DeviceVariationInfo { String:OS }
In the database those object are split into the following tables:
Users, Devices, DevieVariationsInfo, UserToDevices
I am trying to query the the list of devices along with their variation info for a certain user, and am using the following query, which always returns a list of 0 items in Devices. I am pretty sure I am doing something wrong here.. =)
private void GetUserDevices(ref User user)
{
User locUSer = user;
if (user != null)
{
var deviesQuery = from dts in _dataConext.DB_UserToDevices
where dts.UserId == locUSer.Id
join ds in _dataConext.DB_Devices on dts.DeviceID equals ds.Id
join dsv in _dataConext.DB_DeviceVariations on ds.Id equals dsv.DeviceId
select new Device
{
Version = ds.Version,
VariationInfo = new DeviceVariation
{
OSVersion = dsv.OS
},
Name = ds.FriendlyName,
Id = ds.Id
};
if (deviesQuery != null)
user.Devices = deviesQuery.ToList();
}
}
A couple of notes:
Is User a class? If so, why are you passing it into GetUserDevices by ref? Don't do that unless you want to change the meaning of that reference.
Also, why are you doing this? User locUSer = user;
Here's how I'd go about debugging your problem: remove parts of that query until you get data back. For example, remove the last join statement, rerun the query, and see where you're going wrong.

Linq one to many insert when many already exists

So I'm new to linq so be warned what I'm doing may be completely stupid!
I've got a table of caseStudies and a table of Services with a many to many relasionship
the case studies already exist and I'm trying to insert a service whilst linking some case studies that already exist to it. I was presuming something like this would work?
Service service = new Service()
{
CreateDate = DateTime.Now,
CreatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First(),
Description = description,
Title = title,
CaseStudies = (from c in db.CaseStudies
where c.Name == caseStudy
select c),
Icon = iconFile,
FeatureImageGroupId = imgGroupId,
UpdateDate = DateTime.Now,
UpdatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First()
};
But This isn't correct as it complains about
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.DataClasses.EntityCollection'
Can somebody please show me the correct way.
Thanks in advance
Yo have to add the query result to the case studies collection instead of trying to replace it.
var service = new Service { ... };
foreach (var caseStudy in db.CaseStudies.Where(s => s.Name == caseStudyName)
{
service.CaseStudies.Add(caseStudy);
}
You can wrap this in an extension method and get a nice syntax.
public static class ExtensionMethods
{
public static void AddRange<T>(this EntityCollection<T> entityCollection,
IEnumerable<T> entities)
{
// Add sanity checks here.
foreach (T entity in entities)
{
entityCollection.Add(entity);
}
}
}
And now you get the following.
var service = new Service { ... };
service.CaseStudies.AddRange(db.CaseStudies.Where(s => s.Name == caseStudyName));

linq help - newbie

how come this work
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == 1
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
but this does not
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == postId
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
The issue is most likely in the implementation of the query provider.
pcm.PostId == 1
and
pcm.PostId == postId
actually have a big difference. In the expression tree the first is generated as a ConstantExpression which doesnt need to be evaulated.
With the second, the compiler actually generates an inner class here (this is the _DisplayClassX that you see). This class will have a property (will most likely be the same name as your parameter) and the expression tree will create a MemberAccessExpression which points to the auto-generated DisplayClassX. When you query provider comes accross this you need to Compile() the Lambda expression and evaluate the delegate to get the value to use in your query.
Hope this helps.
cosullivan
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit : Have you tried to return a List<> collection ? or an Enumerable type?
Edit : What is the real type of the item and query may not be iterable

Resources