【发布时间】:2020-08-16 04:39:06
【问题描述】:
假设
// connection strings and other configurations is not mentioned for simplicity
MyDbContext context = new MyDbContext();
Var Entities = Context.Set< table1>();
Var list = Entities.ToList();
LINQ to SQL 生成以下 SQL 查询:
Select col0, col1, isdeleted, coln
From table1
这段代码很完美,返回了一个 table1 对象的列表(假设有 20 行)。
我的要求是:
// looking for a function or anything. This is my need
Entities.AddDefaultFilter("isdeleted", false);
// expected rows (18 rows, 2 rows have isdeleted = true)
// Those should be excluded
Var list = Entities.ToList();
我以非常糟糕的方式实现了这一点:
var list = Entities.ToList();
return list.Where(x => ((bool?)x.GetType().GetProperty("IsDeleted").GetValue(x)) == false).ToList();
这段代码很完美,只返回满足isdeleted = false条件的行。
这很糟糕,因为它首先从数据库中加载所有行,然后过滤/删除具有isdeleted = true 值的行。
如果 table1 有 1M 行和 300K 行,isdeleted = true 则需要额外的时间和内存。
抱歉语法错误。
谢谢。
【问题讨论】:
-
我不能这样称呼:var list = Entities.Where(e=>e.IsDeleted==false).ToList();因为它是一个泛型存储库,泛型类型 T 没有属性 IsDeleted。
标签: c# sql-server asp.net-core .net-core ef-core-3.0