Home > front end >  List<string> assignment and initialization with new List<string> getting error
List<string> assignment and initialization with new List<string> getting error

Time:01-29

I'm developing a website with Asp.Net core 3.1 and C# version 8.0. I have a class named "ApiResult"

public class ApiResult
{
    public bool IsSuccess { get; set; }
    public List<string> Message { get; set; } = new List<string>();
    public object Data { get; set; }
}

and I'm going to use it on a controller

public async Task<string> CreateBook(BooksCreateEditViewModel ViewModel)
    {
        if (await _UW.BookRepository.CreateBookAsync(ViewModel))
        {
            return new ApiResult
            {
                IsSuccess = true,
                Message = new List<string> { "Your job has done" } ,
            };
        }
        else
            return "We got an error!!!";
    }

But unfortunately, I got a weird error: "Cannot implicity convert ApiResult to the string"

CodePudding user response:

Try changing the return type of your CreateBook method to return Task<ApiResult>. You should then also tweak what you return from your else clause - perhaps set the isSuccess property from your ApiResult model to false. Something along these lines:

public async Task<ApiResult> CreateBook(BooksCreateEditViewModel ViewModel)
    {
        if (await _UW.BookRepository.CreateBookAsync(ViewModel))
        {
            return new ApiResult
            {
                IsSuccess = true,
                Message = new List<string> { "Your job has done" } ,
            };
        }
        else
            return new ApiResult
            {
                IsSuccess = false,
                Message = new List<string> { "We got an error!!!" } ,
            };
    }

You could simplify the if statement so that you don't create the ApiResult object in two different places, this answer is just given as an example.

CodePudding user response:

Yeah you can't implicitly convert a class to string

You could do it like this:

public async Task<ApiResult?> CreateBook(BooksCreateEditViewModel ViewModel)
    {
        if (await _UW.BookRepository.CreateBookAsync(ViewModel))
        {
            return new ApiResult
            {
                IsSuccess = true,
                Message = new List<string> { "Your job has done" }
            };
        }
        else return null;
    }
  • Related