Using the principle of separation of request commands in MVC controllers

I like the idea of splitting the command request , but I canโ€™t see how to use it in the action of the MVC controller, which adds the entity, and after adding it, a new object identifier is required.

For example, in the simplified example below, a service is used to create a new item:

public ActionResult Assign(AssignViewModel viewModel) { var newItem = _AssignItemService.AssignItem(viewModel.ItemName, viewModel.ItemValue); return RedirectToAction("ListItem", new {id = newItem.Id); } 

But when I redirect to the action that will display the new item, I need to know the identifier of the newly created item so that it can be retrieved from the database. Therefore, I must ask the service to return the newly created element (or at least its identifier).

In pure CQS, the command has no return value, so the above pattern is not valid.

Any advice gratefully received.

+6
source share
3 answers

You must pass AssignItem instance of โ€œItemโ€ to the AssignItem method (or regardless of your entity name), which is created from the viewmodel values, then the method should not return anything, instead it just updates the object identifier property, which makes it a Command method.

Then you can use entity.Id for anything.

+4
source

I think you are stuck in a pedantic point.

A query is when you want to ask a question in the database, for example: "How many customers west of the Mississippi purchased red items during June?" This is a request. Returning an identifier during insertion is not a typical request as such.

As with most other software developments, this model is not absolute. Even Fowler says he wants to tear it apart when it's convenient:

The appearance of a stack is a good example of a modifier that changes state. Meyer correctly says that you can avoid this method, but this is a useful idiom. Therefore, I prefer to follow this principle when I can, but I am ready to break it in order to get pop.

If you really want to get the last added identifier from the database separately from its insertion, you can use something like Area ID . But I think you add complexity without any additional benefits.

+8
source

The way to do this should be to force the caller to specify an identifier for the new object (which most likely implies using a GUID as a key).

However, in my experience, imposing a rule (purist) on the fact that the team cannot return the result will cause problems with a small gain.

0
source

Source: https://habr.com/ru/post/914818/


All Articles