C
C#•3y ago
bookuha

Converting id's to entities

I have this kind of request: BookRequest( string name, string description, ICollection<long> authorIds) I want to map it to an entity. I consider there approaches: 1) Map it partially (name, description), then in a handler find the authors associated with passed authorIds and populate the entity Authors collection with them 2) Inject DB context into Mapper profile instance (Is it SOLID? Somebody said that it is not, but I feel like it is pretty ok) 3) Implement id->entity converter class to retrieve Authors by Ids and use it in the mapper. Which do you consider the best? What are the other options?
17 Replies
Tvde1
Tvde1•3y ago
in what piece of code do you want to get the entities associated with the authorIds? somewhere it should do
var authors = await _context.Authors
.Where(a => authorIds.Contains(a))
.ToListAsync();
var authors = await _context.Authors
.Where(a => authorIds.Contains(a))
.ToListAsync();
bookuha
bookuhaOP•3y ago
In a mapping method Preferably But not sure if it is ok to do
Tvde1
Tvde1•3y ago
like in an extension method?
bookuha
bookuhaOP•3y ago
yes
Tvde1
Tvde1•3y ago
ToDto() something?
bookuha
bookuhaOP•3y ago
yes!
Tvde1
Tvde1•3y ago
I would never do any database calls in such a method
bookuha
bookuhaOP•3y ago
yeah. so another approach is to make a class that would do it? or idk
Tvde1
Tvde1•3y ago
usually for me a controller calls a Service (e..g AuthorService) class which would do everything needed for the functionality
bookuha
bookuhaOP•3y ago
I think of calling ToDto() that doesnt maps ids, and then map them manually in a service
Tvde1
Tvde1•3y ago
class BookService
{
public void AddBook(BookRequest request)
{
// get authors
// validate stuff
// create book
}
}
class BookService
{
public void AddBook(BookRequest request)
{
// get authors
// validate stuff
// create book
}
}
a BookRequest already feels like a DTO
bookuha
bookuhaOP•3y ago
yes, it is is it appropriate naming?
Tvde1
Tvde1•3y ago
well is it to create a book, retrieve a book, update a book? I'd put a verb in front of it
bookuha
bookuhaOP•3y ago
create
Tvde1
Tvde1•3y ago
CreateBookRequest then :D
bookuha
bookuhaOP•3y ago
ty! the problem is I may get confused because I already have CreateBookCommand from mediatR 😄 but i guess it is a bad practice to use mediatr objects there thank you!
Tvde1
Tvde1•3y ago
wait with doing db calls until your class actually needs them, then you're sending less data through events

Did you find this page helpful?