.NET CORE 2 EF包括 [英] .NET CORE 2 EF Include

查看:96
本文介绍了.NET CORE 2 EF包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的.net核心和EF.

I am using new .net core and EF.

我需要包含linq命令的帮助.我有一些1:N模型,如果集合包含一些标记为已删除"的数据,我不想包含它们.

I need help with include linq command. I have some 1:N models and if the collection contais some data marked like deleted I do not want to include them.

该怎么做?

var company = await _context.Company
                .Include(y => y.Administrators)
                .Include(y => y.CompanyPartTimers)
                .Include(z => z.WorkPlaces)
                .Include(z => z.Requirements)
                .FirstAsync(x => x.Id == id);

如果我添加条件

.Include(z => z.WorkPlaces).Where(x=>x.WorkPlaces.Where(x=>!x.IsDeleted))

它不起作用.如何正确编写呢?

It doesn't work. How to write this correctly?

接下来的事情是我有IDeletable接口,如果我有一些自定义linq表达式并且可以用于ex会更好.

Next thing is I have IDeletable Interface and it would be better if I had some custom linq expression and could do for ex.

.Include(z => z.WorkPlaces).GetNonDeleted()

有人知道怎么做吗? 我尝试过这样的事情

Does anyone know how to do it? I tryed something like this

public static class LinqExtension
    {
        public static IEnumerable<T> GetActive<T>(this IEnumerable<T> source) where T : class, IDeletable
        {
            return source.Where(x => x.IsDeleted);
        }
    }

谢谢大家.

推荐答案

您可以在DbContext中配置查询过滤器.

You can configure a Query Filter in your DbContext.

modelBuilder.Entity<Administrator>()
            .HasQueryFilter(admin => !EF.Property<boolean>(admin, "IsDeleted"));

应该可以解决问题

参考链接: https://docs.microsoft.com/zh-cn/ef/core/querying/filters

这篇关于.NET CORE 2 EF包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆