How to work with DTOs in Controller of WebAPI?

ado.net-entity-data-model asp.net-web-api c# dto entity-framework-6

Popular Answer

Simply put, your new edit indicates you don't needId and Member residences in yourAddressDTO model. And you should mould the outcome into aList<AddressDTO> when you are heading backList<Address> .

Therefore, merely delete any unnecessary attributes fromAddressDTO You then mould the outcome by making new choicesAddressDTO and setting properties:

var result = db.Address.Select(x=> new AddressDTO()
                                   { 
                                       Street = x.Id, 
                                       Street_Number = x.Street_Number,
                                       City = x.City,
                                       Country = x.Country
                                   }).ToListAsync();

You may add such a function Object() { [native code] } to the linq to make it shorter.AddressDTO :

public AddressDTO(Address x)
{
    Street = x.Id;
    Street_Number = x.Street_Number;
    City = x.City;
    Country = x.Country;
}

and in the controller:

var result = db.Address.Select(x=> new AddressDTO(x)).ToListAsync();

You may depend on certain object mappers, such as auto mapper, as described in a response, even while working on a big project.

6
11/12/2016 4:30:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow