将DBSet限制为实体的子集 [英] Restrict DBSet to a subset of entities
问题描述
我希望在创建我的数据库上下文时可以指定一个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屋!