Advice on POCO Validation with ASP.NET MVC/Entity Framework

前端 未结 2 1054
一向
一向 2021-02-02 17:23

Here\'s the scenario:

  • ASP.NET MVC2 Web Application
  • Entity Framework 4 (Pure POCO\'s, Custom Data Context)
  • Repository Pattern
  • Unit of Wor
2条回答
  •  眼角桃花
    2021-02-02 18:17

    Hey, probably a bit late but here goes anyway...

    It all depends on your architecture, i.e. Is there a logical seperation, in your application: UI, Service Layer, Repository Layer. If you are hooking onto the Save event, how exactly will that be done? From what I observed you would be calling the repository Layer for Persistance only right? However you are hooking onto the save event, giving control back to the Service Layer/ Business Layer whatever then forcing the save through right?

    I personally feel the Service layer/ Business Layer should take care of it in completion then say, hey mr repo layer -> save this object.

    With regards to validation, Data Annotations should be used with the UI, so simple valiation like [Required] etc, this will be helpful with the Client Side validation but complex business logic or complex validation should be hooked into the service layer/ business layer, that way it is reusable across all entities/ objects/ POCOS etc.

    With regards to preventing certain private fields not being tampered with... only allow your service layer/ business layer to actually set the object that will be persisted (yes i mean :) ...) hand coding it, I felt this was the safest option for me anyway, as I will simple do:

    var updatedpost = _repo.GetPost(post.postid);
    updatedpost.comment = post.comment;
    updatedpost.timestamp = datetime.now;
    

    Kind of wasteful but that way your buseinss layer takes control, however this is just my experience I may be wrong, I have read a lot into model binding, validaiton and other stuff however there seemed to be cases where things never work as expected e.g. [Required] attribute (see Brad WIlson's) post.

提交回复
热议问题