I need to add this simple statement to each SQL query, per table:
WHERE De开发者_运维技巧leted = 0
Is there any easy way of doing? I mean I need to filter all records, preferrably in the edmx file.
Sounds like you want to add a WHERE to your object sets by default. I don't know if you can do that by default, but a couple ways I can think of to accomplish this are:
1) Use views to give you the WHERE clause and build your entities off the views. I've never actually done this, so I don't know how well views work with EF - if you need to write back to the database, this probably wouldn't work well.
2) Create new properties in a partial class of your EDMX, like:
partial class MyEntities
{
public IQueryable<Foo> ActiveFoos
{
return Foos.Where(f => f.Deleted == 0);
}
}
...
using (var context = new MyEntities())
{
var foo = context.ActiveFoos.Where(f => f.Id == 1).SingleOrDefault();
}
3) Create a child context class and new
out the properties - kind of ugly, but this would be reasonably transparent to the developer once it's built.
public class CustomEntities : MyEntities
{
public new IQueryable<Foo> Foos
{
get { return base.Foos.Where(f => f.Deleted == 0); }
}
}
...
using (var context = new CustomEntities())
{
var foo = context.Foos.Where(f => f.Id == 1).SingleOrDefault();
}
The only reliable way to ensure that Deleted = 0
is used always (including lazy loading, explicit loading and eager loading) is using Conditional mapping. The drawback of conditional mapping is that Deleted
column will not be available in the entity = Delete operation which sets this column must be mapped to stored procedure.
You have to do it at the time you get your results from EntityFramework.
Example:
IEnumerable<TableEntity> filteredResults = TableEntityName.Where(t => t.Delete = 0);
精彩评论