首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用I枚举返回方法

如何使用I枚举返回方法
EN

Stack Overflow用户
提问于 2021-04-05 04:13:40
回答 2查看 40关注 0票数 0

你好,我有这样的域模型

代码语言:javascript
运行
复制
 public string ComponentTitle { get; private set; }
    
 public string componentLatinTitle { get; private set; }

这是我的dto

代码语言:javascript
运行
复制
 public bool IsShow { get; set; }
  
 public string ComponentTitle { get; set; }

现在我想返回我的dto并在GetMethod中用dto映射域,这是我的Controller

代码语言:javascript
运行
复制
[HttpGet]
    public async Task<IEnumerable<StaticComponentDto>> GetStaticComponents()
    {
        return await _staticComponent.GetComponents();
    }

这是我的服务:

代码语言:javascript
运行
复制
 public Task<IEnumerable<StaticComponentDto>> GetComponents()
        {
            var components =  _repository.Query().GetAllAsync();
            return new StaticComponentDto()
            {
                ComponentTitle = components.ComponentTitle;
            };
        }

我的服务没有用:

我犯了这样的错误:

代码语言:javascript
运行
复制
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  

帮助我实现我的服务,或者如果它有一个文档来实现服务或方法,我会很乐意学习的,谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-05 04:53:57

您将从存储库中获取StaticComponents变量中的所有components。当您返回一个新的StaticComponentDto时,您指的是哪些组件?C#怎么知道的?你需要指定。

有许多方法可以映射所有对象,其中之一是:

您可以遍历components并将它们映射到一个新的IEnumerable<StaticComponentDto>中。

代码语言:javascript
运行
复制
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;

注意:

此外,如果您正在对异步方法进行异步调用(在您的示例中,您是在调用异步存储库方法--),则应该将您的服务方法作为异步。这意味着,在public async Task<IEnumerable<StaticComponentDto>> GetComponents() ()签名中添加GetComponents()关键字

  • 注意到在这种情况下,我们需要等待从存储库调用.
票数 1
EN

Stack Overflow用户

发布于 2021-04-05 04:44:48

我想您需要返回linq select函数:

代码语言:javascript
运行
复制
return components.Select(component => new StaticComponentDto()
{
    ComponentTitle = component.ComponentTitle
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66948162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档