mohsinali1317
mohsinali1317

Reputation: 4425

SqlException: Invalid object name c#

I am trying to connect to localDB in my .net core 2.0 web app. I have created a local db using SQL express.

My appsettings.json looks like this

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Warning"
}
},

"ConnectionStrings": {
"DefaultConnection": "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=Shopping;Integrated Security=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}

}

My Context file looks like this

    public class ProductContext : DbContext
{
    public ProductContext(DbContextOptions<ProductContext> options) 
        :base(options)
    {

    }

    public DbSet<Product> Products { get; set; }
}

My startup file passes context like this

services.AddDbContext<ProductContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

When I am trying to get my products from the Database

        try
        {
            var d = await _context.Products.ToListAsync();
            return View(d);

        }
        catch (Exception e)
        {

        }

I get this exception thrown

"Invalid object name 'Products'."

I am also adding my database image here

enter image description here

I am assuming it has something to do with the database connection?

How do I give path to the file?

Upvotes: 7

Views: 17405

Answers (2)

Anton Gorbunov
Anton Gorbunov

Reputation: 1444

Looks like you have no table Products in the Database.

  1. It may be necessary to specify a different table name using the table mapping attribute ([Table("Product")]) on Model or to start migration / initialization on the database, if this has not already happened.
  2. If there was a problem with the connection - the error would be exactly this, but it looks like you are getting an error ("Invalid object name 'Products'.") directly from the sql server

Upvotes: 19

Yared
Yared

Reputation: 2472

You can use fluent API in OnModelCreating method of ProductContext to map database table with your model. This way you don't need to add attributes in you models.

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

Upvotes: 2

Related Questions