Context: I am converting a program from C# to VB. The program runs with Entity Framework (latest, but not EFCore).
In a C# class, I have an auto-property for a collection, initialised thus:
public virtual ICollection<Student> Students {get; set;} = new List<Student>();
This runs fine with EF.
Converted to VB this becomes:
Public Overridable Property Students As ICollection(Of Student) = New List(Of Student)()
Strangely, the latter seems not work with Entity Framework, yielding a run-time error stating
The property 'Students' ... cannot be set because the collection is already set to an EntityCollection.
I can fix this error by reverting to the older long-winded way to initialise a collection (which I used to have to do in C# also before it had initialization of auto-properties):
Private _students As ICollection(Of Student) = New List(Of Student)
Public Overridable Property Students As ICollection(Of Student)
Get
Return _students
End Get
Set(value as ICollection(Of Student))
_students = value
End Set
End Property
I had thought that the above long-winded code and the single line that replaced it were functionally equivalent. Can anyone explain to me why they are different AND why/how this is different to the C# equivalent (where the long-winded and one-line equivalents appear to have the same behaviour).