C
C#3y ago
Alex Frost

Help with Implicit Explicit operators

This is my operator definition
public static implicit operator EventViewModel(Entry e)
{
EventViewModel viewModel = new EventViewModel();
viewModel.Id = e.Id;
viewModel.Title = e.Title;
viewModel.StartDate = e.DateStart;
viewModel.EndDate = e.DateEnd;
return viewModel;
}
public static implicit operator EventViewModel(Entry e)
{
EventViewModel viewModel = new EventViewModel();
viewModel.Id = e.Id;
viewModel.Title = e.Title;
viewModel.StartDate = e.DateStart;
viewModel.EndDate = e.DateEnd;
return viewModel;
}
I've not been able to find the exacts. With this definition, will it convert from Entry to ViewModel or ViewModel to Entry? Because, with the said implementation, following conversion doesn't work: EventData = Context.Entries.Where(e => e.UserId == UserId); The error is Can't convert from IQueryable<Entry> to IQueryable<ViewModel>
9 Replies
canton7
canton73y ago
It converts an Entry to a EventViewModel, but that doesn't mean you'll get an automatic conversion from an IQueryable<Entry> to an IQueryable<EventViewModel>
Alex Frost
Alex FrostOP3y ago
🙁 So what's the way to do that
canton7
canton73y ago
Particularly as this is going up to a database, and the database has no idea how to run your user-defined conversion .Select(x => (EventViewModel)x)? You need something to convert each element to an EventViewModel
Alex Frost
Alex FrostOP3y ago
Right I used Select but wanted to automate it a bit
canton7
canton73y ago
Although at that point you might as well drop the operator, as it really is code smell, and just do .Select(x => new EventViewModel(x))
Alex Frost
Alex FrostOP3y ago
.Select(x => new EventViewModel(x)) that seems like a constructor, so I'll have to implement a constructor for ViewModel, right?
canton7
canton73y ago
Yeah, that'll be neater than an implicit conversion
Tvde1
Tvde13y ago
In my projects, we make an extension method .ToDto() or sorts and then do
query.Select(x => x.ToDto())
query.Select(x => x.ToDto())
To map from entities to DTOs
Alex Frost
Alex FrostOP3y ago
Perfect, thanks a bunch you guys 🙂
Want results from more Discord servers?
Add your server