I'm new to WebApi, and layered architecture. Below is the structure of my entire project:
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
below is what I've written in the service
below is DTOs class
How can I resolve these errors?
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:
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
).TodoService.Delete
. The value returned should be TodoItem
, not TodoItemDto
. (TodoService.cs
, line 26)_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)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.