Entity Framework 4: Many to Many relationship IQueryable instead of ICollection

不打扰是莪最后的温柔 提交于 2019-12-07 19:45:58

问题


Good morning everyone,

I am trying to tackle a problem I run into with EF code first. My schema is the following

   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 have written code with which I am able to retrieve a category from the database without actually knowing that its a category. From then on I must retrieve a single article of that category again without knowing that its an article. For categories I am relying on the ContentNode base class and for Articles on the IUrlNode interface.

Category retrieval works fine and with a single query but after I actually get the category I have to use reflection to get the navigation property pointed by the RouteChild attribute to find that single article that matches my criteria. Problem is that the navigation property type is ICollection which means that it will at best use lazy loading and will bring all the articles from the database and will find the one I am looking for in memory.

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

Entity Framework Code First IQueryable

Is there a way to have that navigation property as IQueryable or some other design that can go around this limitation?


回答1:


No there is no way to have navigation property as IQueryable but you can change the collection to IQueryable by using:

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

Generally your "algorithm" looks pretty strange. You want to work with base class but in the same time you want to access child properties. That sounds wrong and it can most probably be solved in better way (non "generic" way is also better).



来源:https://stackoverflow.com/questions/7551988/entity-framework-4-many-to-many-relationship-iqueryable-instead-of-icollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!