Following the tutorial on creating a web API with ASP.NET Core, with the tutorial’s project files for reference, I created the exact project described with the DTO approach, which worked successfully using an in-memory database:
builder.Services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
Now I want to achieve the same outcome using a SQL Server database instead.
So instead of using opt.UseInMemoryDatabase
, I’m now using opt.UseSqlServer(<MY-CONNECTION-STRING>)
in its place. This is the only line of code that I have changed from the tutorial.
I set up a SQL Server with a table for TodoItems
with 3 columns named Id
, Name
and IsComplete
, which matches the names of the TodoItemDTO
class fields.
The problem I am experiencing with the SQL Server is that the program is trying to post the Secret
field from the TodoItem
object.
I get this exception:
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘Secret’.
Why does the DTO approach described in the tutorial work for an in-memory database but not with a SQL Server database?
2
Answers
The in-memory implementation does not behave the same as a real SQL server. There is a statement made in this article: https://learn.microsoft.com/en-us/ef/core/testing/#involving-the-database-or-not which suggests:
Because table TodoItems not has column ‘Secret’.
I think table was define before.
you can use migrate to add new column or ignore mapping that column.