简体   繁体   中英

Entity Framework Core 3.0 error - SqlException: Invalid column name

I get the following error when I migrate my ASP.NET Core MVC from 2.2 to 3.0

SqlException: Invalid column name 'ContractProfileContractId'.

My statement which throws the error:

var totalemployees =   _context.EmployeeProfile.Where(x => x.Active == true).ToList();

When I add the column ContractProfileContractId to the Employees table, the apps works, but I need to add more and more columns for other tables.

I started coding this app in .NET Core 1.1 (2017), migrated it to 2.0, 2.1 and 2.2 (1 year ago) and now to 3.0.

I tried 3.1 migration and same problem exists.

The application passed the login screen without any error. The error appears only after trying to query from the database using EF.

Any ideas?

It look like that EF Core is generating for you a foreign key in your model.

Please check your model and context to see if you have some relationships declared and where the foreign key isn't declared into DBB accordingly to conventions (ie EntityId for the foreign key).

If so then you can decorate your foreign key property in your POCO class (but i'm pretty sure it could also be configured during the data context definition)

/// The DBB Foreign key property
[ForeignKey("RelationProperty")]
[Required]
public int IdRelationProperty { get; set; }


/// 
public virtual XXXType RelationProperty{ get; set; }

I had this same issue on a .net core 2.2 to 3.1 migration. In my case our model never correctly had all the navigation properties / foreign keys setup. Then I guess because of some change in EF it now generates the model different (probably more accurately).

To diagnose the issue you can add a new migration and see what columns/FKs that ef believes it needs to correct. Then go back to your model builder and correct setup the missing relations.

Then you can remove the migration and try again eventually you should see that adding the migration results in an empty migration.

It looks like you forgot to generate migration after adding new field.

dotnet ef migrations add YourMigration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM