且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架约束的导航属性

更新时间:2023-01-14 22:10:49

(我假设,因为使用的是EF code-首先, [关键] 属性。)

(I assume you are using EF Code-First, because of the [Key] attribute.)

有不同的方式来加载导航属性和相关的实体,你可以申请一个过滤器,其中的一些方式,但不是所有的:

There are different ways to load navigation properties and related entities and you can apply a filter for some of these ways but not for all:

  • 延迟加载:

  • Lazy loading:

您导航酒店为虚拟使延迟加载在所有工作:

Your navigation property has to be virtual so that lazy loading works at all:

public virtual IList<Comment> Comments { get; set; }

加载父:

var blogPost = context.BlogPosts.Find(1);
foreach (var comment in blogPost.Comments) // lazy loading triggered here
{
}

您不能在此应用过滤器。延迟加载将永远载入的所有的给定的博客发表评论。

You can't apply a filter here. Lazy loading will always load all comments of the given blog post.

预先加载:

var blogPost = context.BlogPosts.Include(b => b.Comments)
    .SingleOrDefault(b => b.Id == 1);

您可以不适用过滤器包括。预先加载将永远载入的所有的给定的博客发表评论。

You can't apply a filter in Include. Eager loading will always load all comments of the given blog post.

显式加载:

加载父:

var blogPost = context.BlogPosts.Find(1);

当你现在加载注释可以应用过滤器:

You can apply a filter when you load the comments now:

context.Entry(blogPost).Collection(b => b.Comments).Query()
    .Where(c => !c.AuditInfo.Deleted.HasValue)
    .Load();

  • 投影:

  • Projection:

    您可以在投影性能应用过滤器:

    You can apply a filter in the projected properties:

    var blogPost = context.BlogPosts
        .Where(b => b.Id == 1)
        .Select(b => new
        {
            BlogPost = b,
            Comments = b.Comments.Where(c => !c.AuditInfo.Deleted.HasValue)
        })
        .SingleOrDefault();
    

  • 这是不可能使用某种形式的全球过滤策略的模型定义,因此,这个过滤器被申请的所有的上述自动和无明确装载明确规定,并在投影的方法例。 (我想你心里有这样一个全球模型定义,但是这是不可能的。)

    It is not possible to apply some kind of global filter policy in the model definition so that this filter gets applied for all methods above automatically and without specifying it explicitly in the explicit loading and in the projection example. (I think you have such a global model definition in mind, but that's not possible.)