EF6 POCO INotifyPropertyChanged without viewmodels

為{幸葍}努か 提交于 2019-12-01 21:57:25

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

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

Option 2 - Introduce DTOs/ViewModels and use AutoMapper

  1. Add a new folder to your project (or create another project)
  2. Add a new POCO generation T4 template
  3. Modify it slightly to conform to your view model of choice
  4. Use AutoMapper to map these Dto/ViewModels to the entities

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

EDIT - examples Here's a T4 template with my entities, that I added the [DataContract] attributes to allow the POCOs to be serialized.

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)#>
<#
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!