问题
A friend asks "Do you have examples or docs on how to inspect the Breeze change-set data on the server and perform server side validation and security checks before committing the data to the database?" My answer follows.
回答1:
See the "Custom EFContextProvider" topic in the documentation which describes the Breeze.NET facilities for this purpose.
Although this topic targets the
EFContextProvider<T>
specifically, most of the points apply to the base class,ContextProvider<T>
, which is helpful when saving to any kind of data store (see the "NoDb" sample for example).
The app produced by the BreezeMvcSpa template offers a taste of save validation (understood in the broadest sense to include security checks).
The BreezeMvcSpa template will be released Feb 2013 in conjunction with the "ASP.NET and Web Tools 2012.2")
Look at Models/TodoRepository.cs which inherits from EFContextProvider<T>
. It overrides BeforeSaveEntity(entityInfo)
to confirm that you are always updating/deleting a TodoList
/TodoItem
that belongs to the current user. It also assigns the current user to a new TodoList
. In a real app, this would be a dispatcher to some helper classes dedicated to validating specific entity types, a point I slightly elaborate below.
There are two other important overrides:
BeforeSaveEntities(saveMap)
gives you a chance to examine the entire change-set at once. This is a great way to make validate the entire change-set as a whole perhaps to ensure that this save request makes sense as a single transaction. It's also a good place to do some cross-entity checking. BeforeSaveEntities(saveMap)
is called after calling BeforeSaveEntity(entityInfo)
for each entity individually.
BeforeSaveEntities(saveMap)
might be a good dispatch point for delegating validation to dedicated helper classes. I doubt that I would put all of my validation logic in one big ContextProvider
class. I don’t mind that all save activity funnels through the ContextProvider.SaveChanges
gate but I don’t want to do all the work in the ContextProvider
itself.
SaveChangesCore
is the other important override. That’s where you do any final pre-save preparation and hand the change-set to something that actually performs the database save (e.g., the DbContext.SaveChanges
method). You could intercept the result of the save operation before returning control to the ContextProvider
.
Note also that, when using the DbContext
, EF applies the validations you prescribe in model attributes, both the standard set and your custom validation attributes.
I have more save advice but this is probably enough to digest right now.
来源:https://stackoverflow.com/questions/14913498/how-do-i-inspect-change-set-data-on-the-server-before-saving-it