I have built a SQLExpress DB with SSMS and I have used the following command to create the class Models of my DB.
Scaffold-DbContext "Data Source=[Removed]\SQLExpress;Initial Catalog=Warehouse;Integrated Security=True"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models –Verbose –Force
Everything seems to create correctly except when I change the name of the DBContext
Property to retrieve the entity... Here is what I have:
DB: I have one table called "BOX"
. This is the class that is created for it from the Scaffold-DBContext
call. ID
is defined in the DB as the Primary Key.
public class Box
{
public int Id { get; set; }
public double Height { get; set; }
public double Width { get; set; }
public double Length { get; set; }
}
This is the DBContext
class that was created for it:
public class WarehouseContext : DbContext
{
public WarehouseContext(DbContextOptions<WarehouseContext> options)
: base(options)
{
}
public DbSet<Box> Box { get; set; }
}
here is the Controller call I make it it:
public async Task<IActionResult> Index()
{
return View(await _BoxDBContext.Box.ToListAsync());
}
All of this above works perfectly fine, but I don't like that the property in my DBcontext
to retrieve boxes is called Box
. I want it called Boxes
like such.
public class WarehouseContext : DbContext
{
public WarehouseContext(DbContextOptions<WarehouseContext> options)
: base(options)
{
}
public DbSet<Box> Boxes { get; set; }
}
public async Task<IActionResult> Index()
{
return View(await _BoxDBContext.Boxes.ToListAsync());
}
But when I change the name it fails to work, stating the following error:
An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'Boxes'.
System.Data.SqlClient.SqlCommand+<>c. b__107_0(Task result)
I cleaned the Solution multiple time, rebooted the machine and still the error happens...
So I tried this, I added a new property to return the exact same thing, but gave it a different name... So I now have Boxes
and TextBoxes
public class WarehouseContext : DbContext
{
public WarehouseContext(DbContextOptions<WarehouseContext> options)
: base(options)
{
}
// I left this method here..
public DbSet<Box> Boxes { get; set; }
// and added this one.
public DbSet<Box> TextBoxes { get; set; }
}
public async Task<IActionResult> Index()
{
return View(await _BoxDBContext.Boxes.ToListAsync());
}
This now works???????
Does anyone know why this might be happening? I obviously can't keep it like this..