Entity Framework 4: Many to Many IQueryable Relationships Instead of ICollection

Good morning everybody,

I am trying to solve a problem that I encountered with EF code. My scheme is as follows

public class Article : IUrlNode { [Key] public Guid ArticleID { get; set; } public string Title { get; set; } public DateTime DateCreated { get; set; } public DateTime DateUpdated { get; set; } public string Summary { get; set; } [System.ComponentModel.DataAnnotations.InverseProperty("CategoryArticles")] public virtual IQueryable<Category> ArticleCategories { get; set; } public string FriendlyUrl { get; set; } } [RouteChild("CategoryArticles")] public class Category : ContentNode { public Guid ServiceId { get; set; } [System.ComponentModel.DataAnnotations.InverseProperty("ArticleCategories")] public virtual IQueryable<Article> CategoryArticles { get; set; } } 

I wrote code with which I can get a category from a database without knowing what its category is. From now on, I should again get one article in this category, not knowing what her article is. For categories, I rely on the base class ContentNode and articles in the IUrlNode interface.

The category search works fine with a single query, but after I really got the category, I have to use reflection to get the navigation property indicated by the RouteChild attribute to find this single article that matches my criteria. The problem is that the type of the navigation property is ICollection, which means that at best it will use lazy loading and will output all the articles from the database and find the one I am looking for in memory.

My problem is also described in this previous post (not me):

Entity Framework Code IQueryable First

Can this navigation property be used as IQueryable or some other design that can get around this limitation?

+2
c # entity-framework-4
source share
1 answer

There is no navigation property like IQueryable , but you can change the collection to IQueryable using:

 IQueryable<Article> query = context.Entry(category).Collection(c => c.articles).Query(); query.Where(...).Load(); 

As a rule, your β€œalgorithm” looks rather strange. You want to work with the base class, but at the same time you want to access the child properties. This does not sound right, and it can most likely be solved in the best possible way (not the "general" way is also better).

+4
source share

All Articles