Home > other >  How to Avoid Error -- System.InvalidCastException: Unable to cast object to type 'System.Collec
How to Avoid Error -- System.InvalidCastException: Unable to cast object to type 'System.Collec

Time:01-03

I am a beginner to ASP.NET MVC coding using C#, and during one of the learning sessions I was implementing relationship between 2 SQL Server tables using Entity Framework.

However, when I tried running it on localhost, I got this error:

System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'Dev.DB.SUST_INC_TRCKR_DTLS' to type 'System.Collections.Generic.ICollection`1[Dev.DB.SUST_INC_TRCKR_DTLS]'.
Source=Dev.DB

StackTrace:

at Dev.DB.DBOperations.SustHCRepository.Onboard_Sust_HC(HC_TBL hc) in C:\Users\NT_ID\source\repos\Training\Dev.DB\DBOperations\SustHCRepository.cs:line 32
at MVC_Lesson13.Controllers.CreateController.Index(HC_TBL hc) in C:\Users\NT_ID\source\repos\Training\MVC_Lesson13\Controllers\CreateController.cs:line 30
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.b__0() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.b__2()

Below are the both the classes I am using with entity .tt classes.

Primary key table's model class:

enter image description here

Foreign key table's model class:

enter image description here

Entity .tt C# for primary key table:

enter image description here

Entity .tt C# for foreign key table:

enter image description here

Database operations repository C# (this where I get the error):

enter image description here

I surely know for a fact that I am making some mistake. However, none of the google or stack forums could provide the solution on this.

Please help

CodePudding user response:

Next time pls post the code instead of pics or your post will be closed.

But because of New Year holiday, fix the line where is the error message , it should be

SYST_IC_TRCKR_DTLS= new List<SYST_INC_TRCKR_DTLS> {SYST_INC_TRCKR}
  • Related