Object-oriented design: Saving complex objects

后端 未结 2 1946
别那么骄傲
别那么骄傲 2021-01-07 11:39

I have a complex domain model built on top of a legacy system that I\'ve built most of the \"get\" methods for - typically just by passing around database primary key IDs. E

相关标签:
2条回答
  • 2021-01-07 12:14

    You should investigate the popular object-relational mapping frameworks for .NET. A lot of people have handled this problem before, and some of the smartest ones have shared the fruits of their labor with us. They've got loads of features and the most popular ones are heavily tested.

    Every few days, it seems, someone new asks for .NET ORM recommendations, so there are plenty of Stack Overflow topics to help guide you. For example:

    • What are your favorite .NET Object Relational Mappers (ORM)?
    • What ORM frameworks for .NET Do You Like Best?
    • Which ORM for .net would you recommend?

    (If you search on 'ORM' and '.NET' you'll turn up many many more matches.)

    In typical usage, the UI developer only deals with high-level parent objects (called 'aggregate roots' in the language of Domain-Driven Design). They use the ORM as a Repository and it ensures all the operations in a given Save are bundled together in sensible transactions. (You still need to enforce validity per business rules in your domain objects.)

    Here's a simplified look at what UI code would look like:

    // Given an IRepository implemented by your ORM,
    ICustomer customer = repository.Get(customerId);
    
    // ... do stuff to customer and its child objects ...
    
    repository.Save(customer);
    
    0 讨论(0)
  • 2021-01-07 12:32

    You can make your objects all expose the same method, call it AttemptSave, and calling this method on the parent object will result in it calling in cascade those methods of all children.

    The method could return a boolean value indicating the success of the operation. No need to throw exceptions to make it easy for the UI developer.

    Then expose a method GetValidationErrors. If AttemptSave returned false, then the UI developer should call this method to retrieve and display errors.

    Alternatively, you can add a validation method Validate which will precheck the object hierarchy. You can return validation errors via GetValidationErrors. Then the call to AttemptSave will be performed. Should it fail, you can return the errors with GetOperationErrors.

    Something in the philosophy of SQL. Either your query succeeded or not, you can always look at @@ROWCOUNT to get an idea whether the query did at least part of the job.

    0 讨论(0)
提交回复
热议问题