全局过滤mvc操作结果 [英] Filter mvc action results globally
问题描述
我的sql数据库中有几个表。所有表都包含分支ID。我可以在我的控制器动作中过滤结果,例如
var members = db.Members.Where(x => x.BranchID = 1)
i必须在每个动作中执行此操作。
有没有其他方法可以这样做?
i have several tables in my sql database. all the table contains branch id. i can filter the results in my controller action like
var members=db.Members.Where(x=>x.BranchID=1)
i have to do this in every action.
is there any other method to do so ?
推荐答案
您可以创建一个帮助程序类来为您完成,然后在每次需要时调用它。
所以你可以有一个各种各样的静态助手方法。
如:
You could just create a helper class that does it for you, then call that each time you want it.
So you could have a static helper with various methods.
Such as:
GetBrandOneMembers()<br />
GetBrandTwoMembers()<br />
GetMembersForBrans(List<int> brandIds)</int>
等。
etc.
您好,
使用静态列表:
Hi,
Use Static List :
public static IEnumareble<member> members= new Lazy<ienumareble><member>>(() => GetMember );
private static IEnumareble<member> GetMember()
{
using ( var db=new YourDBContext()){
return db.Members.Where(x=>x.BranchID=1).ToArray();
}
}
</member></member></ienumareble></member>
你可以创建一个iterface
you can create an iterface
public interface IBranchable
{
int BranchID {get;set;}
}
然后你需要让每个拥有BranchID的实体类来实现IBranchable接口
then you need to make every entity class that has BranchID to implement IBranchable interface
public partial Member : IBranchable
{
}
// and every other entity that have BranchId ...
并且最后你可以使用扩展方法来过滤
and at the end you can can make an extension method to filter
public static ExtensionsMethods
{
public static IEnumerable<IBranchable> GetByBranchId(this IEnumerable<IBranchable> source, int branchId)
{
return source.Where(x=> x.BranchID == branchId);
}
public static IEnumerable<IBranchable> GetByBranchId1(this IEnumerable<IBranchable> source)
{
return source.Where(x=> x.BranchID == 1);
}
}
通常我这样做,代码更加清晰可读
用法:
db.Members.GetByBranchId(1)
db.OtherEntity.GetByBranchId(1)
更新:
如果您的控制器直接使用实体框架,那么你可以创建一个包装器来公开由您的branchId预过滤的实体集
usually i act like this and the code is a lot more clear and readable
usage :
db.Members.GetByBranchId(1)
db.OtherEntity.GetByBranchId(1)
UPDATE :
if your controller uses directly entity framework, then you could create a wrapper to expose entity sets pre-filtered by your branchId
public class InternalContext: IDisposable
{
protected bool disposed = false;
private YourEntityContext db;
public int BranchId { get; private set;}
public InternalContext(int branchID)
{
db = new YourEntityContext();
BranchId = branchID;
}
public IEnumerable<Member> Members
{
get {
return db.Members.GetByBranchId(BranchID);
}
}
// and so on
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
db.Dispose();
}
disposed = true;
}
public void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
用法:
使用(var db = new InternalContext (1))
{
var members = db.Members;
}
usage :
using(var db = new InternalContext(1))
{
var members = db.Members;
}
这篇关于全局过滤mvc操作结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!