Home > Net >  Getting a SqlException 0x80131904, Invalid object name 'SiteToSites'
Getting a SqlException 0x80131904, Invalid object name 'SiteToSites'

Time:10-28

I am getting a SqlException 0x80131904 while trying to fetch all records from a table. The error message is: Invalid object name 'SiteToSites'

I have looked here on Stack Overflow for this error and found lots of posts on it and answers. I've checked out the answers, but none address what I'm seeing.

There's a table in the database named SiteToSite. I am using EF Core 6, in a .NET 6 ASP.NET MVC app.

In a service class I have the following to get all the records from a table named SiteToSite:

        public IEnumerable<SiteToSite> GetAll()
        {
            return _context.SiteToSites.OrderBy(s => s.SiteToSiteID);
        }

In the controller I have the following command to call GetAll():

        public IActionResult Step1()
        {
            IList<SiteToSite> sites;
            sites = siteToSiteService.GetAll().ToList();
            var firstSite = sites.First() ?? new SiteToSite();
            return View(firstSite);
        }

The fourth line in the Step1 action method is where the error is raised.

In the DbContext class here's how the DbSet for SiteToSite is defined:

public virtual DbSet<SiteToSite> SiteToSites { get; set; } = null!;

I don't see what's wrong. There is a SiteToSites defined in the DbContext class. The table exists. The properties in the model class match the columns in the SQL database. And furthermore, I've got the same logic for a different table and model class, with its own GetAll() method in its service class and controller. So, why am I getting the 0x80131904 error with this class, but not with the other class?

I'm using VS 2022 and EFCore 6

CodePudding user response:

EF Core is looking for a SiteToSites table but I think the correct name is SiteToSite.

Try configuring explicitly the name of the table SiteToSite.

modelBuilder.Entity<SiteToSite>().ToTable("SiteToSite");

CodePudding user response:

Just add the code below in your DbContext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SiteToSite>()
        .ToTable("SiteToSite");
}

I tested it and it works fine in my code.

If not recognized, you can try to install Microsoft.EntityFrameworkCore.Relational.

There is another easiest way: Define it as SitetoSite in DbContext class.

public virtual DbSet<SiteToSite> SiteToSite { get; set; } = null!;

And in GetAll():

public IEnumerable<SiteToSite> GetAll()
{
    return _context.SiteToSite.OrderBy(s => s.SiteToSiteID);
}
  • Related