How can I change an Entity Framework ICollection to be an ObservableCollection?

c# entity-framework mvvm


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; }
5/29/2015 10:54:33 AM

Popular Answer

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(
            "{0}using System;{1}" +
            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())#>>();
1/1/2017 7:08:32 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow