Reputation: 4425
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
I am assuming it has something to do with the database connection?
How do I give path to the file?
Upvotes: 7
Views: 17405
Reputation: 1444
Looks like you have no table Products
in the Database.
[Table("Product")]
) on Model or to start migration / initialization on the database, if this has not already happened."Invalid object name 'Products'."
) directly from the sql serverUpvotes: 19
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