【问题标题】:tell EF not to consider records with a bit field = 1 (isDeleted)告诉 EF 不要考虑位字段 = 1 (isDeleted) 的记录
【发布时间】:2011-02-23 08:35:22
【问题描述】:

所有表都有一个位字段IsDeleted

有没有办法告诉 EF 在查询时不要考虑它们。

或者我只需要每次都指定这个,比如Where(o => o.IsDeleted != true)

(先使用EF4 CTP5代码)

【问题讨论】:

  • +1 好问题。标准 EF 可以做到这一点,但我无法先在 EF 代码中找到它。
  • @Ladislav - 只是好奇,如何在标准 EF 中做到这一点?或者答案是否足够长,我可以将其作为问题发布? ;)
  • @Yakimych:打开设计器,选择一些实体,打开上下文菜单并选择表映射。在表映射窗口展开树,你会看到<Add a Condition>

标签: entity-framework entity-framework-4 ef-code-first


【解决方案1】:

我通过在我的通用存储库中执行此操作解决了这个问题,我还为没有 isDeleted 的实体创建了一个只读存储库(它们根本不由应用程序管理,只是读取),只读存储库获取所有记录

简单的 repo 继承了 readonly 并覆盖了不应返回标记为 isDeleted = false 的实体的方法;

应该标记为 IsDeleted = true 的实体继承自 DelEntity

public class DelEntity : Entity, IDel
{
    public bool IsDeleted { get; set; }
}

我的通用存储库:

public class Repo<T> : ReadRepo<T>, IRepo<T> where T : DelEntity, new()
    {
        public Repo(IDbContextFactory a) : base(a)
        {
        }

...
        public override IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
        {
            return c.Set<T>().Where(predicate).Where(o => o.IsDeleted == false);
        }

        public override IEnumerable<T> GetAll()
        {
            return c.Set<T>().Where(o => o.IsDeleted == false);
        }
    }

我的只读操作存储库

public class ReadRepo<T> : IReadRepo<T> where T : Entity, new()
    {
        protected readonly DbContext c;

        public ReadRepo(IDbContextFactory f)
        {
            c = f.GetContext();
        }

        public T Get(long id)
        {
            return c.Set<T>().Find(id);
        }

        public virtual IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
        {
            return c.Set<T>().Where(predicate);
        }

        public virtual IEnumerable<T> GetAll()
        {
            return c.Set<T>();
        }

        public int Count()
        {
            return c.Set<T>().Count();
        }

    }

这个解决方案有点针对我的情况,但希望你能从中得到一些想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2020-03-22
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多