将DBSet限制为实体的子集 [英] Restrict DBSet to a subset of entities

查看:124
本文介绍了将DBSet限制为实体的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF 4构建一个多租户应用程序,我有一个共享数据库,许多实体都有一个CustomerID字段。我想知道是否有办法可以从我的DBContext在我的DBSet级别强制执行一个CustomerID查询。



我希望在创建我的数据库上下文时可以指定一个CustomerID,并将DBSets包装为始终包含一个(x => x.CustomerID == custID)我不需要担心在我的应用程序中添加这个逻辑,但是我无法找到任何可能的东西,表明可能的。



非常感谢

解决方案

强烈推荐在单独的 服务层中执行此操作DbContext,因为它将在这个级别上更容易执行。



如果你坚持在DbContext级别执行这个操作,这里是一个可以做你想做的例子。 / p>

  class MyContext:DbContext 
{
private readonly int _customerId;

public MyContext(int customerId)
{
_customerId = customerId;
}

public DbQuery&MyEntity> MyEntities
{
get
{
return(DbQuery)Set&MyEntity>()。其中​​(e =&e; e.CustomerId == _customerId);
}
}

protected override OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< MyEntity>();
}
}

这个最大的问题是你不能确保从MyEntities返回的查询将不会被进一步修改,以包含其他客户的实体。


I am building a multi-tenant application using EF 4, I have a shared database an many entities have a CustomerID field. I was wondering if there was a way I could enforce a CustomerID query at my DBSet level from my DBContext.

I was hoping I could specify a CustomerID when I create my DB context, and wrap the DBSets to always include a (x => x.CustomerID == custID) so I don't need to worry about adding this logic all over my application, but I haven't been able to find anything that suggests its possible

Many thanks

解决方案

I strongly recommend doing this in a separate service layer on top of your DbContext since it will be much easier to enforce at that level.

If you insist on doing it at the DbContext level, here is a sample that does what you want.

class MyContext : DbContext
{
    private readonly int _customerId;

    public MyContext(int customerId)
    {
        _customerId = customerId;
    }

    public DbQuery<MyEntity> MyEntities
    {
        get
        {
            return (DbQuery)Set<MyEntity>().Where(e => e.CustomerId == _customerId);
        }
    }

    protected override OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyEntity>();
    }
}

The big problem with this is that you cannot ensure that the query returned from MyEntities won't be further modified to include entities for other customers.

这篇关于将DBSet限制为实体的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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