Reputation: 33
hello there i have domainmodel like this:
public string ComponentTitle { get; private set; }
public string componentLatinTitle { get; private set; }
and this is my dto:
public bool IsShow { get; set; }
public string ComponentTitle { get; set; }
now i Want To return my dto and map the domain with dto in GetMethod, This is my Controller:
[HttpGet]
public async Task<IEnumerable<StaticComponentDto>> GetStaticComponents()
{
return await _staticComponent.GetComponents();
}
and this is my service:
public Task<IEnumerable<StaticComponentDto>> GetComponents()
{
var components = _repository.Query().GetAllAsync();
return new StaticComponentDto()
{
ComponentTitle = components.ComponentTitle;
};
}
my service didnt work :
and i have a error like this:
Severity Code Description Project File Line Suppression State
Error CS1061 'Task<IEnumerable<StaticComponent>>' does not contain a definition for 'ComponentTitle' and no accessible extension method 'ComponentTitle' accepting a first argument of type 'Task<IEnumerable<StaticComponent>>' could be found (are you missing a using directive or an assembly reference?) IM.Application
help me to implement my service or if it have a document to implement services or methods i'll be happy to learn thank you
Upvotes: 0
Views: 65
Reputation: 563
I guess you need to return with linq select function:
return components.Select(component => new StaticComponentDto()
{
ComponentTitle = component.ComponentTitle
});
Upvotes: 0
Reputation: 450
You're getting all the StaticComponents
from repository in your components
variable. When you're returning a new StaticComponentDto
, which of the components are you referring to? How does C# know? you need to specify.
There are a number of ways you can map all the objects, one of them is:
You can iterate through the components
and map them into a new IEnumerable<StaticComponentDto>
.
var components = await _repository.Query().GetAllAsync();
var componentsDto = new List<StaticComponentDto>();
foreach (var component in components)
{
var componentDto = new StaticComponentDto();
componentDto.ComponentTitle = component.ComponentTitle;
componentsDto.Add(componentDto);
}
return componentsDto;
Note:
Also, if you are making asynchronous calls to asynchronous methods (in your case, you're calling the asynchronous repository method - GetAllAsync()
), you should make your service method as async. Which means, you add the async keyword in the GetComponents() signature:
public async Task<IEnumerable<StaticComponentDto>> GetComponents()
Notice how in this case, we need to await the call from repository.
Upvotes: 1