Home > other >  ASP.NET MVC: Method-Based LINQ Query of SQL Db as IEnumerable object
ASP.NET MVC: Method-Based LINQ Query of SQL Db as IEnumerable object

Time:10-13

I am trying to query a database for all its record into an IEnumerable object. Here are the relevant codes:

Db Context Snippet

namespace WebApplicationTemp.Data
{
    public class CSVMetaDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            var connectionString = string.Format(@"Data Source=source;Initial Catalog=CSVMetaDb;Integrated Security=True;MultipleActiveResultSets=True");
            options.UseSqlServer(connectionString);
        }
        public DbSet<CSVMeta> CSVMetas { get; set; }
    }
}

Startup.cs Snippet

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<CSVMetaDbContext>();
}

Controller Snippet

private readonly CSVMetaDbContext _db;

public CSVController(ICSVService csvService, CSVMetaDbContext db)
{
     _csvService = csvService;     //Can be ignored, for other applications using IService Interface
     _db = db;
}

public IActionResult Database()
{
    IEnumerable<CSVMeta> objList = _db.CSVMeta;
    return View(objList);         //Razor View not created yet due to error
}

The Model works and contain the desired data using Microsoft SQL Server Management Studio.

However, _db.CSVMeta contains the following error:

Error   CS1061  'CSVMetaDbContext' does not contain a definition for 'CSVMeta' and no accessible extension method 'CSVMeta' accepting a first argument of type 'CSVMetaDbContext' could be found (are you missing a using directive or an assembly reference?)

May I check how I can fix this?

CodePudding user response:

Looks like typo: the collection name is CSVMetas:

IEnumerable<CSVMeta> objList = _db.CSVMetas; 

CodePudding user response:

I think it is a typo. In your db context class the property is named CSVMetas but in your controller you are calling _db.CSVMeta. You are missing an s.

  • Related