Skip to content
Advertisement

System.InvalidCastException: When trying to add an object to a SQL database using Entity Framework in C#

I am trying to use Entity Framework in C# to add objects to a SQL database. The data is coming from a combination of textboxes and datepicker controls. I’m guessing this is a problem with how I’m parsing the data but the error seems vague to me. Any advice would be greatly appreciated.

Here is the code that adds the data to the database.

Here is the code for the EF entity class:

Here is the schema for my database table.

Advertisement

Answer

I realized after staring at the code for 15 minutes that I neglected to specify the .Text property on these lines

In addition I used this link from a related SO post to verify I was converting my values correctly. https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings?redirectedfrom=MSDN

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