本文介绍了实体框架4:多对多的关系,而不是IQueryable的ICollection的的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家早上好,

我试图解决我遇到与EF代码第一个问题。我的模式是以下

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; }
}



我写的代码与我能够检索从一个类别数据库实际上不知道它的一个类别。从那时起,我必须检索类别的一篇文章再次不知道它的文章。对于类,我依靠ContentNode基类和物品的IUrlNode接口。

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.

分类检索工作正常,并用一个单一的查询,但之后我居然得到我不得不使用反射来获取由RouteChild指向的导航属性的类别属性,发现单文章符合我的标准。问题是,在导航属性类型是ICollection的,这意味着将在最好地利用迟缓装载并且将把所有从数据库中的文章,并会找到一个我在存储器寻找

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):

有没有办法有一个导航属性为IQueryable的或一些其他的设计,可以绕过这个限制?

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

推荐答案

没有就没有办法让导航属性为 IQueryable的,但你可以通过改变集合的IQueryable

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).

这篇关于实体框架4:多对多的关系,而不是IQueryable的ICollection的的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:21