Skip to content
Advertisement

SqlClient.SqlException: Invalid column name ClassNameId While fetching data from Fluent API

I am new to this EF,I am tring to fetch data from Sql Db table, and it gives me error like invalid classNameId error.

DbContext:

I have use Fluent API for get data from MSSql.

Advertisement

Answer

The problem is the invalid ForeignKey annotation here

ForeignKey is confusing attribute because it changes the meaning of the argument depending on where it is applied. When applied on FK property it indicates the name of the navigation property. And when applied on navigation property it indicates the name of the FK property.

In your case, it is applied on FK property, but specifies the same property name, so it is simply ignored and EF uses the default conventional name for the FK property associated with the List<OtherClass> OtherClassList relationship, which is why you are getting the non existing column.

To fix the problem, either apply the attribute on the navigation property of the other class (because you have no navigation property in the class that needs FK):

or (preferably) configure it with fluent API:


In case you have reference navigation property, in addition to the above data annotation solution, you could also use

or

or the fluent API .WithOne() must be changed to .WithOne(e => e.ClassName).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement