Entity Framework, soft-deleting and queries

2019-04-27 07:35发布

问题:

So here's my situation:

I'm soft-deleting some rows in a table, using a IsDeleted flag, so that a can keep a trace of my archived data. I do so by overriding the SaveChanges statement in my ObjectContext.

The question is: how can I select only the row(s) that have IsDeleted == false, without having to specify && !IsDeleted in every queries?

Is there a way I can specify this on my context directly?

tkx!

回答1:

You could define a view over your table and query that view instead:

CREATE VIEW dbo.ActiveData
AS
  SELECT (list of columns)
  FROM dbo.YourTable
  WHERE IsDeleted = 0

And then in your EDMX model, read your data from the ActiveData view instead of the base table.



回答2:

If you right-click an EntitySet in the model viewer, and click "Table Mapping", there is an area where you can "Add a Condition". This should do what you're asking, although you might be better off using a View instead, as per marc_s's suggestion.



回答3:

This is an old question now, but for anyone new coming here. As of EF 6 you really should be using interceptors for this type of query. It places a query inside of the SQL query as it runs and filters records based on the flag.

See the following for more info:

Soft Deleting Entities using Interceptors