MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.3k stars 328 forks source link

ProjectToType with single entitiy #522

Closed heggi closed 1 year ago

heggi commented 1 year ago

Standard code to get one entity from database if entity exists:

var entity = context.Set<ExampleModel>()
    .Where(m => m.Id = id)
    .FirstOrDefault();

Here entity variable has a nullable type ExampleModel? and I can check it for null (if null, no entity found in db)

Now I want add ProjectToType

var entity = context.Set<ExampleModel>()
    .Where(m => m.Id = id)
    .ProjectToType<ExampleDTO>()
    .FirstOrDefault();

Here entity variable has a not nullable type ExampleDTO If entity in database is absent, we anyway got instance of ExampleDTO

Here we need a some method (for example ProjectToTypeSingle) which will return IQueryable<TDestination?> Or has any workaround?

andrerav commented 1 year ago

Hehe @heggi you are destroying me with all these issues:D Does it work as expected if you add a ToList() like this?

var entity = context.Set<ExampleModel>()
    .Where(m => m.Id = id)
    .ToList()
    .ProjectToType<ExampleDTO>()
    .FirstOrDefault();
heggi commented 1 year ago

I do more experiment. My mistake was in ExampleDTO (I create it as struct)

If ExampleDTO is struct, I got this problem. And if I replace ProjectToType via Select(x => new ExampleDTO { ... }) got same problem. And problem here in FirstOrDefaultAsync, not ProjectToType :) FirstOrDefaultAsync return default value, and default value for struct - is empty struct, not null :)

If change type of ExampleDTO to class or record, all works as expected, FirstOrDefaultAsync return null.

Sorry for disturbing.

andrerav commented 1 year ago

Ah okay, good to know :) Glad you figured it out!