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条答案
按热度按时间isr3a4wc1#
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:
The in-memory provider will not behave like your real database in many important ways. Some features cannot be tested with it at all (e.g. transactions, raw SQL..), while other features may behave differently than your production database (e.g. case-sensitivity in queries). While in-memory can work for simple, constrained query scenarios, it is highly limited and we discourage its use.
brc7rcf02#
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.