简体   繁体   English

实体框架,其中Deleted = 0

[英]Entity framework where Deleted = 0

I need to add this simple statement to each SQL query, per table: 我需要将此简单语句添加到每个表的每个SQL查询中:

WHERE Deleted = 0 删除位置= 0

Is there any easy way of doing? 有什么简单的方法吗? I mean I need to filter all records, preferrably in the edmx file. 我的意思是我需要过滤所有记录,最好是在edmx文件中。

Sounds like you want to add a WHERE to your object sets by default. 听起来好像您想在默认情况下将WHERE添加到对象集。 I don't know if you can do that by default, but a couple ways I can think of to accomplish this are: 我不知道您是否可以默认执行此操作,但是我可以想到的几种方法是:

1) Use views to give you the WHERE clause and build your entities off the views. 1)使用视图为您提供WHERE子句,并根据视图构建您的实体。 I've never actually done this, so I don't know how well views work with EF - if you need to write back to the database, this probably wouldn't work well. 我从来没有真正做到过这一点,所以我不知道视图在EF中的工作情况如何-如果您需要写回数据库,则可能效果不佳。

2) Create new properties in a partial class of your EDMX, like: 2)在EDMX的部分类中创建新属性,例如:

partial class MyEntities
{
    public IQueryable<Foo> ActiveFoos
    {
        return Foos.Where(f => f.Deleted == 0);
    }
}
...
using (var context = new MyEntities())
{
    var foo = context.ActiveFoos.Where(f => f.Id == 1).SingleOrDefault();
}

3) Create a child context class and new out the properties - kind of ugly, but this would be reasonably transparent to the developer once it's built. 3)创建一个子上下文类并new创建属性-有点丑陋,但这对开发人员而言,一旦构建起来就相当透明。

public class CustomEntities : MyEntities
{
    public new IQueryable<Foo> Foos
    {
        get { return base.Foos.Where(f => f.Deleted == 0); }
    }
}
...
using (var context = new CustomEntities())
{
    var foo = context.Foos.Where(f => f.Id == 1).SingleOrDefault();
}

The only reliable way to ensure that Deleted = 0 is used always (including lazy loading, explicit loading and eager loading) is using Conditional mapping . 确保始终使用Deleted = 0 (包括延迟加载,显式加载和急切加载)的唯一可靠方法是使用条件映射 The drawback of conditional mapping is that Deleted column will not be available in the entity = Delete operation which sets this column must be mapped to stored procedure. 条件映射的缺点是,在实体=删除操作中设置了该列,该Deleted列在实体中将不可用,该操作必须将此列映射到存储过程。

You have to do it at the time you get your results from EntityFramework. 您必须在从EntityFramework获得结果时执行此操作。

Example: 例:

IEnumerable<TableEntity> filteredResults = TableEntityName.Where(t => t.Delete = 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM