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

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();

Related

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.

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

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)

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

ActionResult Details needs to resolve FK from List to display Name?

I have a FK in my Details ViewModel and when the View binds to the ViewModel I only get the FK back (expected). The FK is a reference to a simple ID/Name type table. I also have a Strongly typed List in the VM representing that FK-referenced table. I want to do something like
<div class="display-field">#Model.ManufacturersList.Find(x => x.ID == Model.softwaremanufacturerid))</div>
While this will return the the instance I want...I can't figure out how to get the "Name" attribute to display.
Sorry if this is more a Lamda question but thought I'd try all the same
Thanks
If .ManufacturersList.Find(x => x.ID == Model.softwaremanufacturerid) returns what you want, don't do it in the View. The View should only display data, while the model layer should really be doing the searching (.Find)
In your view model, add a string property for ManufacturerName
public string ManufacturerName { get; set; }
In your controller,
MyViewModel vm = new MyViewModel()
{
ManufacturerName = .ManufacturersList
.Find(x => x.ID == theFKAlreadyInTheViewModel)
};
return View(vm);
Then in your view,
#Model.ManufacturerName
OR, more simply, you could use the ViewBag
ViewBag.ManufacturerName = YourManufacturersList
.Find(x => x.ID == theFKAlreadyInTheViewModel);
Then in your View,
#ViewBag.ManufacturerName

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