So I'm pretty far down the rabbit hole of using the Entity Framework designer to make an EDMX that serves as the model in an MVVM project.
I've just come across an issue where I'm pretty sure that the ICollection<>
that was code generated (see below for example) really needs to be an ObservableCollection<>
for binding that collection to a DataGrid
in a view to be successful.
I think I'm getting some hits on the possibility of modifying the EF code generation to make ObservableCollections
rather than ICollections
. Any one ever tried that successfully?
I suppose another option would be have the VM that contains the selected Customer object also contain a local ObservableCollection<Order>
that gets created when the Customer object is selected....I just worry about the context saves and keeping the data in sync.
typical code gen object with an association to a collection of child objects :
public partial class Customer
{
public Customer()
{
this.Orders = new HashSet<Order>();
}
public int Id { get; set; }
public System.DateTime Date { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
That's what I did and what works for me with EF Database first.
That's what you need to be generated:
public partial class Parent
{
public Parent()
{
this.Children= new ObservableCollection<Child>();
}
So that default costructor will be replaced. And ObservableCollection is ICollection, so you don't need to change anything else.
To make this appear every time you update your database model you have to change your .tt file with following parts:
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;{1}" +
"{2}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.ObjectModel;"
+ Environment.NewLine + "using System.Collections.Generic;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}
and this:
foreach (var navigationProperty in collectionNavigationProperties)
{
this.<#=code.Escape(navigationProperty)#> = new ObservableCollection<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With