[英]SqlException: Invalid object name c#
I am trying to connect to localDB in my .net core 2.0 web app.我正在尝试在我的 .net core 2.0 Web 应用程序中连接到 localDB。 I have created a local db using SQL express.我使用 SQL express 创建了一个本地数据库。
My appsettings.json looks like this我的 appsettings.json 看起来像这样
{
"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?我如何提供文件的路径?
Looks like you have no table Products
in the Database.看起来您在数据库中没有表Products
。
[Table("Product")]
) on Model or to start migration / initialization on the database, if this has not already happened.可能需要在 Model 上使用表映射属性( [Table("Product")]
)指定不同的表名,或者在数据库上开始迁移/初始化(如果这还没有发生)。"Invalid object name 'Products'."
) directly from the sql server如果连接有问题 - 错误就是这个,但看起来您直接从 sql server 收到错误( "Invalid object name 'Products'."
)You can use fluent API in OnModelCreating
method of ProductContext
to map database table with your model.您可以在ProductContext
OnModelCreating
方法中使用 fluent API 将数据库表映射到您的模型。 This way you don't need to add attributes in you models.这样您就不需要在模型中添加属性。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.ToTable("Product");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.