Search code examples
c#asp.net-coreautomapperasp.net-core-webapidto

N-layered Web Api using automapper to pass DTOs between controller and service layers error


I'm new to WebApi, and layered architecture. Below is the structure of my entire project:

enter image description here

I want to know how to pass entities from controller to service and get back again from service to controller

below is what I've written in the controller

enter image description here

below is what I've written in the service

enter image description here

below is DTOs class

enter image description here

below are the errors enter image description here

How can I resolve these errors?


Solution

  • There are many things wrong here. I think they mostly stem from confusion between your DTO and model classes.

    So these errors are all because you declared your ITodoService to use/return TodoItem instances, but you're using TodoItemDto instead:

    1. TodoService.GetAll, TodoService.GetByid and TodoService.Delete all require TodoItem on the interface, but you used TodoitemDto when you implemented them in TodoService. (The three errors on line 13 of TodoService.cs).
    2. You're not returning a value at all from TodoService.Delete. The value returned should be TodoItem, not TodoItemDto. (TodoService.cs, line 26)
    3. _dorepo.Delete() returns void. You cannot assign it to a variable. I can't help you there, because I don't know what you intended to do. (TodoService.cs, line 29)
    4. Because TodoService.GetAll is incorrectly defined to return TodoItemDto, the value from _dorepo.GetAll cannot be returned. The fix is to to change the function declaration to return TodoItem, as mentioned in point 1 above. (TodoService.cs, line 37)

    You don't show the code for TodoController, but I'm guessing the last two errors are similar.

    My advice is to do one of the following: 1. Throw out the DTO objects. They're a nice idea, but they don't serve a real purpose if they only serve to confuse you, or 2. Make the DTO's interfaces that you implement on the model objects. All the other classes and interfaces refer only to those interfaces, as far as possible. That way, you can still define them on the API and use them as you wanted, but they won't get in your way. And you can always just cast to the model object where needed. Alternatively, 3. Add a constructor on your DTO that accepts the model object as parameter and lets the DTO wrap the model object. And add a ToModelObject function to the DTO, which will let you convert easily to the model object.

    I really do think that you should focus first on getting a basic controller working as expected, and only then add in the DTO. That way, you're focusing on one complication at a time.