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?
This typically means 1 of 2 things... you've referenced an object (table, trigger, stored procedure,etc) that doesn't actually exist (i.e., you executed a query to update a table, and that table doesn't exist). Or, the table exists, but you didn't reference it correctly...
SqlClient. SqlException (0x80131904): A network-related or instance-specific error occurred while extablishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
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 serverYou 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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With