Cannot retrieve table rows from ASP.Net core razor page

Viewed 88

I am new to C# and ASP.Net core razor pages. I think this is a simple question but after many hours I still have not been able to resolve it.

I am (currently) putting my business logic (eg Maintenance logic) in root/BLL/MaintenanceBLL/Maintenance.cs

In trying to read records in the Maintenance table from Maintenance.cs. I get the error

CS0030 Cannot convert type 'Club.Models.Maintenance' to 'Club.BLL.MaintenanceBLL.Maintenance'

The term ForEach is redlined in the code by VS2019. I cannot resolve this error. Any assistance would be appreciated.

My code is:

Namespace Club.BLL.MaintenanceBLL
{
    public class Maintenance
    {
        private readonly Club.Data.ApplicationDbContext _context;

        public Maintenance(Club.Data.ApplicationDbContext context)
        {
            _context = context;
        }
        public Maintenance()
        {
        }
      
        public void DoMaintenance()
        {
            //Parse Maintenance table and action those items
            //where Active=True and ActionDate has passed
           
            var maintenances = _context.Maintenance;
            foreach (Maintenance m in maintenances)
            {
                //do something
            }
        }
    }
}
1 Answers

Use var to auto detect type like

foreach (var m in maintenances)

or

foreach (Club.Models.Maintenance m in maintenances)

The reason is you must be having two Maintenance classes one would be under namespace Club.Models and other one under namespace Club.BLL.MaintenanceBLL.

As your current code is under Namespace Club.BLL.MaintenanceBLL; when you write Maintenance it will try to find Maintenance m in maintenances class under current namespace or all namespace which you have mentioned with using ....

You have not added using Club.Models; so it won't find Club.Models.Maintenance and your foreach (Maintenance m in maintenances) will treated as Club.BLL.MaintenanceBLL.Maintenance.

But your _context.Maintenance would be DbSet<Club.Models.Maintenance> so when you write foreach (var m in maintenances) it will expect to loop with Club.Models.Maintenance object. And you mentioned Maintenance which would be considered as Club.BLL.MaintenanceBLL.Maintenance so your compiler is showing the red line with error.

Related