Home > OS >  how to give DTO to LINQ select many query in c#
how to give DTO to LINQ select many query in c#

Time:04-23

How to give DTO to select or SelectMany

public class PersonDTO
            {
                public int Id { get; set; }
                public string Name { get; set; }
                public string UserName { get; set; }
                public string Email { get; set; }
            }

var person = _context.Persons.Where(x=>x.PersonId==1).SelectMany(PersonDTO);

I want to build a service that I give model or DTO and it returns only those raws that are given in the model or DTO but only from the person table or user detail table

which means something like graphql that get data by DTO, and DTO could be Only Name or UserName or Email or all of them, any Idea?

CodePudding user response:

_context.Persons.Where(x => x.PersonId == 1).Select(x => typeof(PersonDTO)); won't automagically map your type.

What you probably want is something like this, when doing it "manually":

_context.Persons
           .Where(x => x.PersonId == 1)
           .Select(x => new PersonDto(){
                Id = x.Id,
                Name = x.Name,
                UserName = x.UserName,
                Email = x.Email
            });
  • Related