linq to entity - include with lambda expression - linq

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

Related

MVC 3 controller GroupBy View error

Im creating an MVC 3 view from a controller. My model "MyList", contains a large number of records. When I create my model using the following linq statement:
var model = _db.MyList.GroupBy(r => r.myKey);
I'm getting the error: "The model item passed into the dictionary is of type 'System.Collections.GenericlList' 1... but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable' ...
In the view I have the following code in the first line:
#model IEnumerable<MyApp.Models.MyList>
I tried returning
return View(model.ToList());
from the controller, but no joy. What am I missing?
model.ToList() will return a List<T> where T is MyList. Your model type is straight MyList. If the var declaration you have above already returns MyList, just do return View(model).
This one was dogging me all morning. I found the answer to my question in the following post:
Linq Distinct() by name for populate a dropdown list with name and value
I basically return the following:
public static IEnumberable<MyModel> FindTheKeys(this IQueryable<MyModel> myList)
{
return myList.OrderBy(r => r.AreaKey);
}
and then performed the select as indicated in the above post.
var model = _db.MyModel.FindTheKeys().GroupBy(r => r.AreaKey).Select(g => g.First());
GroupBy returns a collection of IGrouping<TKey, TSource>, not MyList (which is strange anyways, you wouldn't have a list of a list.
It doesn't even make much sense to convert a GroupBy into a list anyways. Did you actuall mean OrderBy?

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

How does this RavenDB linq query work

I was looking at the source code for RacoonBlog trying to find a way in RavenDB to query on a collection contained in a document. I did read about indexes and Map / Reduce and failed to find my answer.
In the PostsController there is an ActionResult called Tag that takes a string parameter and contains the following linq query.
var posts = RavenSession.Query<Post>()
.Include(x => x.AuthorId)
.Statistics(out stats)
.WhereIsPublicPost()
.Where(post => post.TagsAsSlugs.Any(postTag => postTag == slug))
.OrderByDescending(post => post.PublishAt)
.Paging(CurrentPage, DefaultPage, PageSize)
.ToList();
The Where extension method calls TagsAsSlugs and performs an Any, TagsAsSlugs looks like this.
public IEnumerable<string> TagsAsSlugs
{
get
{
if (Tags == null)
yield break;
foreach (var tag in Tags)
{
yield return SlugConverter.TitleToSlug(tag);
}
}
}
So since the TagsAsSlugs property loops over the collection of tags does the query require that all posts are returned so that each post can have its Tags collection iterated over?
I doubt this is the case since Oren's blog is so fast.
Jackson,
No, that is NOT how it works. We are doing the work during indexing (the TagsAsSlugs is actually computed on save time), and then we save TagsAsSlugs into the index.
We query the index for tags that exists there.
In short, we don't do any computation, certainly not on the client side.

Linq Order By not working

The Linq query "order by" is not working and I've followed all the suggestions found on your site and other sites. Any assistance would be appreciated.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p);
return results;
}
Thanks for your input!
Yes, this is a WebGet method for a WCF data service. I get a 400 error if I don't return an IQueryable type, so I modified your suggestion a little. Unfortunately, it still seems to disregard any order-by.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
results.OrderBy(p => p.patientname);
return results;
}
I notice you return an IQueryable<T> - are you calling any LINQ methods on the result before you enumerate it?
Not all LINQ methods preserve order. Most commonly, calling Distinct() after you do the ordering will destroy the order.
Since your method is a marked with a WebGet attribute, I'm assuming that you are calling this method from a Web endpoint, therefore you may need to collapse the collection prior to send it through internet.
Try:
[WebGet]
public vw_providercharge_providers[] GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
return results;
}
This way you have the guarantee that the GetChargeProviders method returns and array instead of an linq expression.
Regards,
I found the cause of the issue.
I had not set the "fullname" column as an Entity Key for the "vw_providercharge_providers" data model entity. Only the identity column was set as an Entity Key. I didn't realize that was a requirement to use it in an order by clause.
Thanks again for your input.

How to apply global filter on Entity Framework?

I have a table in my model named Customers with a field IsActive. Whenever I run a query on Customers, only the active customers should be retrieved. I can include the filter in every query, but that doesn't look very. I would like to be able to override the Customers property at the Object Context lever, but I am not sure if this is possible. Any help would be very appreciated! Thanks
Although a late response, I will put it here so it can help others.
You can also set a condition for your entity in your edmx file. Select your entity and Goto Mapping Details and create a new condition.
Maybe you could declare new property and use it:
public partial class MyEntities
{
public ObjectQuery<User> ActiveCustomers
{
get
{
return Customers.Where(c => c.IsActive);
}
}
}
I don't know why this is problem for you. You can put one query inside some function:
IEnumerable<Customers> GetActiveCustomers()
{
var activeCustomers =
from cust in db.Customers
where cust.IsActive == true
select cust;
return activeCustomers;
}
And call it every time you like. You can even put active customers in some private List or even better ObservableCollection. Then you can query your result again:
var myCustomers =
from cust in GetActiveCustomers()
where cust.CustomerName == "John"
select cust;
and that's it.
All you need to do is retrieve all of the customers no matter if they are active or not and then use a
foreach(Customer c in Results)
{
if(c.IsActive)
listofactivecustomers.Add(c);
}

Resources