SoftDelete : System.Collections.Generic.List<##.##.Employee>' to 'Microsoft.AspNetCore.Mvc.IActionResult'

I got in error when I try to perform Sofdelete

Cannot implicitly convert type
‘System.Collections.Generic.List<##.##.Employee>’ to
‘Microsoft.AspNetCore.Mvc.IActionResult’.

Here is my index I tried to use ToList() and ToList<Employee>, but it’s not working

public IActionResult Index()
{
    var employees = _dbContext.Employees.Where(x => x.status == '1')
           .ToList();
    return employees;
}

My DbContext:

public class DataContext : DbContext
{   
    public DataContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }

    public override int SaveChanges()
    {
        foreach( var entry in ChangeTracker.Entries())
        {
            var entity = entry.Entity;
            if (entry.State == EntityState.Deleted)
            {
                entry.State = EntityState.Modified; 
                entity.GetType().GetProperty("status").SetValue(entity, '0');
            }
        }
        return base.SaveChanges();
    }
}

Employee:

namespace empAPI.Models
{
    public class Employee
    {      
        public Guid Id { get; set; }
        public char status{ get; set; } = '1';

        public string Name { get; set; }

        public string Department { get; set; }

        public DateTime?  CreatedDate { get; set; } = DateTime.Now;   
    }
}

>Solution :

Change your code to:

public IActionResult Index()
{
    var employees = _dbContext.Employees.Where(x => x.status == '1').ToList();
    return View(employees);
}

Read the following article: Understanding Action Results

A controller action returns something called an action result. An
action result is what a controller action returns in response to a
browser request.

The ASP.NET MVC framework supports several types of action results
including:

  • ViewResult – Represents HTML and markup.
  • EmptyResult – Represents no result.
  • RedirectResult – Represents a redirection to a new URL.
  • JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  • JavaScriptResult – Represents a JavaScript script.
  • ContentResult – Represents a text result.
  • FileContentResult – Represents a downloadable file (with the binary content).
  • FilePathResult – Represents a downloadable file (with a path).
  • FileStreamResult – Represents a downloadable file (with a file stream).

All of these action results inherit from the base ActionResult class.

In most cases, a controller action returns a ViewResult.

Leave a Reply