EF6 POCO INotifyPropertyChanged without viewmodels

I bind directly to the model classes in a WPF application (and skip creating separate viewmodel classes).

Now, moving on to EF6 and DBContext, I ran into the problem of the generated EF POCO classes, as it either looks kind of complicated or it is not even recommended to try to make the INotifyPropertyChanged interface implemented directly in those classes.

Currently

  • I don't want to go back to ObjectContext.
  • I also don't want to change the T4 too much. The suggestions on the web for changing T4 to achieve INotifyPropertyChanged looks too error prone to me.
  • Creating view modes for each class now and only for MVVM would probably be better, but takes a long time to implement as the model is huge.

Do I have any options to get the autogenerated properties of the EF6 POCO class to be notified of their changes?

+3


source to share


1 answer


T4 Templates are your best friends here. You can hardly avoid them Option 1 - Modify existing T4 templates to implement INotifyPropertyChanged

  • Create a base class that implements INotifyPropertyChanged
  • Modify the getter and setters in your T4 templates to notify their property changes

Option 2 - Implementing DTO / ViewModels and Using AutoMapper

  • Add a new folder to the project (or create another project)
  • Add new T4 Generation T4 template
  • Change it slightly to fit your selection model.
  • Use AutoMapper to map these Dto / ViewModels to objects


Option 3 - Implement Postsharp which uses aspect-oriented programming to implement INotifyPropertyChanged with a one line attribute per class - again, you'll need to add a couple of lines to your T4 template

EDIT - Examples Here is a T4 template with my entities that I added [DataContract] attributes to allow serialization of POCOs.

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
    using System.Runtime.Serialization;
[DataContract]
<#=codeStringGenerator.EntityClassOpening(entity)#>
{

// Then further down
    var simpleProperties = typeMapper.GetSimpleProperties(entity);
    if (simpleProperties.Any())
    {
        foreach (var edmProperty in simpleProperties)
        {
#>
    [DataMember]
    <#=codeStringGenerator.Property(edmProperty)#>
<#

      

0


source







All Articles