Entity Framework 4: Is there a way to mark an enti

2019-07-28 18:01发布

问题:

We are using the v4 Entity Framework as part of a new version of an application that includes some significant accounting functions (payment processing, cash balancing, bad check handling, etc.) In all of our previous applications, we have instituted a policy (which I'm told is extremely common in banking/accounting level applications) that there is at least one table, containing the incoming "audit trail" for all money, that can only be written to with new data.

In other words, new information coming in to the system would trigger the creation of a new entity, which would go through the "insert" operation of whatever data layer objects we had and write a new row into the underlying tables. The data layer was intentionally implemented with no update or delete actions for these entities; any changes were tracked as newly inserted adjusting rows.

With EF, we are looking for a way to accomplish the same goal, but in this case, we obviously need to prevent the EF from allowing the updates (as opposed to just not writing the functions). Is there some way to designate an entity in an EF model as being "insert only"?

As I mentioned in the title: I know this can be accomplished by mapping stored procedures to the Insert action but not the Update action. We are looking for some other option, if one exists, for two reasons:

  1. We don't have any stored procedures as yet, and would like to avoid adding another element to our deployment/upgrade process if we can avoid it.
  2. This solution relies on the "absence" of a stored procedure to indicate that the table is special. I'd prefer a solution that relied on a definitive assertion that the "insert-only" is that way on purpose.

回答1:

Yup your best bet is to add .AsNoTracking into the getters for each DbSet in your model. This will mean that EF wont be tracking any entities you get from the database (so wont perform any write backs on them). It also has the added bonus of improving performance.

By forcing all reads to be read only you will eliminate the update path in EF.

Take a look at my post on AsNoTracking, and this article on the EF site