How to add "Select" clause to an EF4.1 query in MVC3 app - linq

I have a simple entity framework query in an MVC3 app, like so
var instances= db.Instances.Include(c => c.CompanyLead).Include(c => c.SalesLead).Include(c => c.Customer);
return View(instances);
This query works fine and essentially returns all instances. However, I need to filter this query and basically add the phrase:
var instances= db.Instances.Include(c => c.CompanyLead).Include(c => c.SalesLead).Include(c => c.Customer)WHERE InstanceType = x
I don't want to revert to an ObjectQuery class with a DB Context object. I thought I would be able to alter this query. Am i wrong?

var instances = db.Instances.Where(c => c.InstanceType ==
"x").Include(c => c.CompanyLead).Include(c =>c.SalesLead).Include(c
=>c.Customer)

Related

using LINQ to receive all data that have property active that is true

I am using MVC3 with EF model first.
I have this LINQ to receive all data:
public List<CoreValueQuestion> GetAllCoreValueQuestions()
{
return db.Question.OfType<CoreValueQuestion>().OrderBy(x => x.QuestionText).ToList();
}
My Question entity have a property that is bool and is called Active, I want to return all questions that have the active = true. How can I do that?
Thanks in advance!
Maybe something like this:
db.Question
.OfType<CoreValueQuestion>()
.Where(a=>a.Active==true)
.OrderBy(x => x.QuestionText)
.ToList();
Or if Active is not nullable column simply do this:
db.Question
.OfType<CoreValueQuestion>()
.Where(a=>a.Active)
.OrderBy(x => x.QuestionText)
.ToList();

Entity Framework Many-To-Many Join Query

I've got a standard social networking paradigm where a User has a collection of friends who are also users.
I'm using Entity Framwork Code First, and my Friend Relationship is defined as follows:
modelBuilder.Entity<User>()
.HasMany(u => u.Friends)
.WithMany()
.Map(m =>
{
m.ToTable("Friendships");
m.MapLeftKey("UserId");
m.MapRightKey("FriendId");
});
What I want to do is to search my users table returning all users with an indicator of whether each returned user is friends with the current user. To be clear, I want to return Users who are Friends and Users who are not friends, but also with a boolean indicating whether each user is a friend. I know how to do this in TSQL its a basic left outer join.
I've seen examples of how to do a left join in LINQ, but all the examples I've seen are joining to a mapped type. My Friendships column doesn't have a Mapped type.
How do I do this in EntityFramework?
var list = context.Users
.Where(u => u.Age >= 20) // sample condition, if you want ALL remove the line
.Select(u => new
{
User = u,
FriendOfCurrentUser = u.Friends.Any(f => f.UserId == currentUserId)
})
.ToList();
Result is a list of anonymous objects containing the user and the boolean friendship indicator. You can also create a helper class UserWithFriendship and project into it (Select(u => new UserWithFriendship { ... }) instead of an anonymous type.

MVC3 ViewModel with multiple LINQ queries, is it making multiple DB calls?

If I am creating a viewmodel to pass to a view and my viewmodel is comprised of several
properties from the same object, how should I create the LINQ query? At the moment I'm doing it like this:
TaskEditViewModel viewModel = new TaskEditViewModel
{
Task = taskRepository.Tasks.FirstOrDefault(t => t.Id == id),
Status = (taskRepository.Tasks.FirstOrDefault(t => t.Id == id).CompletionDate.ToString() == "") ? "close" : "open",
Account = taskRepository.Tasks.FirstOrDefault(t => t.Id == id).Accounts.First()
};
return View(viewModel);
My taskRepository returns IQueryable, so does this mean I am making 3 seperate db calls? Should I be making one call and then building the viewmodel from the results?
I decided to revisit this on its anniversary. I think this would have been making multiple db calls due to lazy loading, so not very efficient.
As Ingo Vals correctly commented, the CompletionDate and Account properties are included in my Task model, so I should have just done something like this:
Task viewModel = taskRepository.Tasks.FirstOrDefault(t => t.Id == id)
return View(viewModel);
Then in my view I can get the CompletionDate and Account properties from the view model

Can I filter the Users returned by GetAllUsers based on a role they are in

I am trying to create an administration interface where users and roles (among other things) can be administered. I have a list of users who can be edited, deleted or viewed. I have this code in the action:
var model = Membership.GetAllUsers()
.Cast<MembershipUser>()
.Select(x => new UserModel
{
UserName = x.UserName,
Email = x.Email,
UserRoles = Roles.GetRolesForUser(x.UserName)
});
return View(model);
This is all fine except that I don't want admins to be able to edit each other. So I need to filter out all users in the "super admin" role. I can certainly figure this out by stepping through each role for each user to see if they are a member. I am wondering if there is a nice sucinct way to do this by filtering the result set in the Select statement, or using Except or Where
I would normally think about the sql I want generated then try write the linq, filtering by roles should be fairly easy with a simple where statement.
However it appears you're trying to abstract each part of the query into smaller bits, this may make it easier to write but can have a devastating effect on performance. For example, I wouldn't be suprised if the GetRolesForUser method you are calling causing an extra database query per user that is returned by GetAllUsers, using the Include method is a much nicer way to get all roles at the same time.
var model = context.Users
.Include(user => user.UserRoles)
.Where(user => !user.UserRoles.Any(role => role == superAdmin)
.Select(user => new UserModel() { UserName = user.UserName, Email = user.Email, UserRoles = user.UserRoles});

linq to entity - include with lambda expression

I have a lite problem i don't really know how to fix. In my example below i would like to select a list of ProductCategories with ProductItems that are active.
public IEnumerable<ProductCategory> ListProductCategories()
{
return _entities.ProductCategorySet.Include("ProductItems").Where(x => x.ProductItems.Active == true).ToList();
}
The problem is that i can't access productItem property Active in my lambda expression, what is the problem? Do I think totaly wrong when im trying to write a linq query like the one above?
There could be more than one item. You probably want to select the categories where all items are active:
return _entities.ProductCategorySet
.Include("ProductItems")
.Where(x => x.ProductItems.All(item => item.Active))
.ToList();

Resources