简体   繁体   English

向linq-to-sql表添加默认的where子句

[英]Adding a default where clause to a linq-to-sql table

Is it possible to add a default where clause to every SQL statement generated by a Linq-to-SQL class? 是否可以向Linq-to-SQL类生成的每个SQL语句添加默认的where子句?

I have a custom DataContext with a Customer class. 我有一个带有Customer类的自定义DataContext。 The Customer class has a Deleted attribute, which is what I want to always be NULL whenever I query the table. Customer类具有Deleted属性,这是我希望在查询表时始终为NULL属性。

So for example, I could write: 因此,例如,我可以写:

List<Customer> customers = db.Customers.ToList<Customer>();

But really get: 但真正得到:

List<Customer> customers = db.Customers.Where(o => o.Deleted == null).ToList<Customer>();

I want to maintain the "deleted" data in my DB, but will never need to see it in my .NET code. 我想在数据库中维护“已删除”数据,但是永远不需要在.NET代码中看到它们。 This sort of default would be handy, so I don't have to remember to add the filter to every query. 这种默认设置很方便,因此我不必记住将过滤器添加到每个查询中。

You can add a new property called ActiveCustomers that returns this: 您可以添加一个名为ActiveCustomers的新属性,该属性返回以下内容:

public IQueryable<Customer> ActiveCustomers {
    get { return db.Customers.Where(e => e.Deleted == null); }
}

Any queries against that property can specify additional Where conditions and otherwise modify the results, but they will always be starting with customers who haven't been deleted. 针对该属性的任何查询都可以指定其他Where条件并以其他方式修改结果,但是它们始终以尚未删除的客户开始 And due to LINQ's deferred execution this statement doesn't cause any additional queries to be executed. 而且由于LINQ的执行延迟,因此该语句不会导致执行任何其他查询。

If you need to ensure no one can access db.Customers you could try to hide it by doing something like this (may not work, I'd need to see your implementation): 如果您需要确保没有人可以访问db.Customers ,则可以尝试通过以下操作将其隐藏(可能无法正常工作,我需要查看您的实现):

public new IQueryable<Customer> Customers {
    get {
      throw new InvalidOperationException("Use property ActiveCustomers instead.");
    }
}

Instead of adding the table to your dbml designer, add a view that contains the default where clause, and just name the view Customer in your dbml. 无需将表添加到dbml设计器中,而是添加一个包含默认where子句的视图,并仅在dbml中将视图命名为Customer。

To allow updates, inserts, and deletes, make sure you select the primary key columns in your DBML designer, and mark their Primary Key property as true. 要允许更新,插入和删除,请确保选择DBML设计器中的主键列,并将其Primary Key属性标记为true。

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

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