繁体   English   中英

无法将实体框架成员更改为受保护

[英]Can't change Entity Framework members to protected

我的应用程序中有以下DbContext类,它们可以正常工作:

public partial class BaseContext : DbContext
{
    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Contact> Contacts { get; set; }
}

public partial class MyAppContext : BaseContext
{
    public new IQueryable<Customer> Customers()
    {
        return base.Customers.Where(n => n.Active == true);
    }

    public new IQueryable<Contact> Contacts()
    {
        return base.Contacts.Where(n => n.Active == true);
    }
}

我希望我的应用程序中对客户或联系人的所有呼叫都可以过滤掉非活动记录。 这种方法效果很好,但是有人可能会在我希望避免的基础上不小心致电客户或联系人。

我认为理想的解决方案是使我的基本上下文中的成员受到保护,以便只能由MyAppContext访问它们,但这失败了,因为在2个DbSet中没有加载任何数据。 例如

public partial class BaseContext : DbContext
{
    protected virtual DbSet<Customer> Customers { get; set; }
    protected virtual DbSet<Contact> Contacts { get; set; }
}

当我将它们设置为protected时,则不会加载任何数据,当它们公开时,everythig很好(但是,这是我想要避免的公开公开)。

有人对如何解决这个问题有任何建议吗?

一个解决方案可能是不使用基类上的DbSet<>属性,而是使用流畅的API声明您的实体类型:

public partial class BaseContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>();
        modelBuilder.Entity<Contact>();
    }
}

然后在MyAppContext ,您可以这样声明属性:

public IQueryable<Customer> Customers =>
    Set<Customer>.Where(n => n.Active == true);
public IQueryable<Contact> Contacts =>
    Set<Contact>.Where(n => n.Active == true);

您可以为其提供实现,而不是使其具有“自动属性”。

public partial class BaseContext : DbContext
{
    protected virtual DbSet<Customer> Customers { get { return this.Set<Customer>(); } }
    protected virtual DbSet<Contact> Contacts { get { return this.Set<Contact>(); } }
}

您可以使用空的DbContext ,然后将其实例传递给通用存储库,如下所示:

public class GenericRepository<T> : IGenericRepository where T : class, new()
{
    private readonly DbContext _context;
    private readonly DbSet<T> _set;

    public GenericRepository(DbContext context)
    {
        _context = _db;
        _set = _context.Set<T>();
    }

    public IQueryable<T> Query => _set.Where(m=>m.Active == true);

    public virtual void Add(T entity) => _set.Add(entity);

    public virtual void Update(T entity) => this._context.Entry(entity).State = EntityState.Modified;

    public virtual void Delete(T entity) =>  _set.Remove(entity);
}

此模式使您可以对实体操作进行精细的分级控制。 您还可以使用不同的查询/更新逻辑来实现不同的存储库。

暂无
暂无

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

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