ASP.NET Core - 无法将类型“System.Collections.Generic.IEnumerable<Models.Student>”隐式转换为“Domain.Models.Student”

问题描述 投票:0回答:3

在我的 ASP.NET Core-7 Web API 项目中,我正在实施 Dapper 来获取所有学生的列表并显示记录。 我有如下所示的代码:

回复:

public class Response<T>
{
    public T Data { get; set; }
    public string Message { get; set; }
    public int StatusCode { get; set; }

    public Response(int statusCode, bool success, string msg, T data)
    {
        Data = data;
        Successful = success;
        StatusCode = statusCode;
        Message = msg;
    }
    public Response()
    {
    }

    public static Response<T> Success(string successMessage, T data, int statusCode = 200)
    {
        return new Response<T> { Successful = true, Message = successMessage, Data = data, StatusCode = statusCode };
    }
    public override string ToString() => JsonConvert.SerializeObject(this);
}

则模型如下图:

型号:

public class Student
{
    public string RegCode { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
}

最后我有这个:

public async Task<Response<IEnumerable<Student>>> GetAllStudentsListAsync()
{
    var response = new Response<Student>();
    using IDbConnection dbConnection = Connection;
    try
    {
        string sQuery = @"SELECT * FROM students";
        dbConnection.Open();
        var listaSql = await dbConnection.QueryAsync<Student>(sQuery);
        response.Data = listaSql;
        response.Message = $"Successfully Retrieved Students List";
        response.StatusCode = (int)HttpStatusCode.OK;
        response.Successful = true;
    }
    catch (Exception ex)
    {
        _logger.Error($"An Error occured " + ex.Message); 
        response.StatusCode = (int)HttpStatusCode.BadRequest;
        response.Successful = false;
        response.Message = $"Student Record Retrieval Failed. Please try again";
        return response;
    }
    finally
    {
        dbConnection.Close();
    }
}

但是我得到了这个错误:

错误 CS0266 无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“Domain.Models.Student”

我如何获得这个决心?

c# asp.net-core dapper
3个回答
1
投票

只要看一眼,您的代码似乎正在尝试将集合隐式转换为 single 对象。

尝试改变这个

 var listaSql = await dbConnection.QueryAsync<Student>(sQuery);

这样的事情:

var listaSql = await dbConnection.QueryAsync<IEnumerable<Student>>(sQuery);

1
投票

看这一行:

var response = new Response<Student>();

GetAllStudentsListAsync
的第二行。你定义了
Response<Student>
所以
Data
变成了
Student
而不是
IEnumerable<Student>
所以你因此得到了一个错误。

替换为:

var response = new Response<IEnumerable<Student>>();

解决问题。


0
投票

请阅读 Stack Overflow 指南并改进您的问题。对于初学者,异常适用于哪些代码?

第二,错误是不言自明的。在某处,您检索了学生列表并尝试分配给 Student 变量。列表 ==> 学生不工作。

如果我猜在哪里发生,这段代码看起来很可疑:

string sQuery = @"SELECT * FROM students";
var listaSql = await dbConnection.QueryAsync<Student>(sQuery);

可能应该是

var listaSql = await dbConnection.QueryAsync<List<Student>>(sQuery);
而不是

© www.soinside.com 2019 - 2024. All rights reserved.