SqlException: Invalid column name 'CreateRequestViewModelRequestId'

asp.net-core-mvc asp.net-mvc c entity-framework-core

Question

I got this error when I tried to save a Response model object into the database by executing this line:

_context.Add(response);
await _context.SaveChangesAsync(); <-- Exception happens in here

The RequestId column in Response table is a foreign key referenced from Request table.

CreateRequestViewModel is the view model I created based on Request model but only have the fields required user to fill in to create a Request.

CreateResponseViewModel is the view model I created based on Response model but only have the fields required user to fill in to create a Response.

The database models are generated using command:

Scaffold-DbContext "Data Source=localhost;Initial Catalog=Test;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

I mapped the value from CreateResponseViewModel object to Response model object in controller action method and tried to save into database, but got this error. My guessing it may be related to cascading update/insert in the Entity Framework Core, but have no idea how to fix it.

Any help would be appreciated. Thank you.

1
-1
1/19/2018 7:58:52 PM

Accepted Answer

Generally speaking, that error occurs when your entities are out of sync with your database. Based on the current state of your entity classes, Entity Frameworks thinks there should be a column named CreateRequestViewModelRequestId, but that column does not actually exist in the table. Short answer is that you need to run a migration to update the database.

However, it's not at all clear what you're doing here and nothing with ViewModel at the end of the class name should ever be going into your database. I imagine you have much deeper issues here that will need to be solved.

1
1/19/2018 7:45:21 PM

Popular Answer

The problem is caused by adding these two lines in the Context class:

public virtual DbSet<CreateRequestViewModel> CreateRequest { get; set; }
public virtual DbSet<CreateResponseViewModel> CreateResponse { get; set; }

Chris is right, ViewModel should not go into database. After remove these 2 lines, it works as expected.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow