EF6 POCO INotifyPropertyChanged 没有视图模型 [英] EF6 POCO INotifyPropertyChanged without viewmodels
问题描述
我一直在 WPF 应用程序中直接绑定到模型类(并跳过创建单独的视图模型类).
I have been binding in WPF application directly to the model classes (and skipping creating individual viewmodel classes).
现在,在切换到 EF6 和 DBContext 后,我遇到了生成的 EF POCO 类的问题,因为它看起来有点棘手,甚至不建议尝试将 INotifyPropertyChanged 接口直接实现到这些类.
Now, after switching to EF6 and DBContext, I face an issue with the generated EF POCO classes since it looks its either kind of tricky or not even recommended trying to make INotifyPropertyChanged interface implemented directly to those classes.
目前:
- 我不想回到 ObjectContext.
- 我也不想过多地改变 T4.网上关于改T4实现的建议INotifyPropertyChanged 对我来说太容易出错了.
- 现在为每个类创建视图模型并纯粹使用 MVVM可能是最好的,但现在需要很多时间来实施,因为模型很大.
我是否有任何选项可以让 EF6 POCO 类自动生成的属性通知它们的更改?
Do I have any options left to get EF6 POCO class autogenerated properties to notify of their changes?
推荐答案
T4 模板是你最好的朋友.你几乎无法避免它们选项 1 - 修改现有 T4 模板以实现 INotifyPropertyChanged
T4 Templates are your best friends here. You almost can't avoid them Option 1 - Modify your existing T4 templates to implement INotifyPropertyChanged
- 创建一个实现 INotifyPropertyChanged 的基类
- 修改 T4 模板中的 getter 和 setter 以通知它们的属性变化
选项 2 - 引入 DTO/ViewModel 并使用 AutoMapper
Option 2 - Introduce DTOs/ViewModels and use AutoMapper
- 为您的项目添加一个新文件夹(或创建另一个项目)
- 添加新的 POCO 生成 T4 模板
- 稍微修改它以符合您选择的视图模型
- 使用 AutoMapper 将这些 Dto/ViewModel 映射到实体
选项 3 - 实施 Postsharp,它使用面向方面的编程来实施具有单行属性的 INotifyPropertyChanged每个班级 - 再次,您必须在 T4 模板中添加几行
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
编辑 - 示例这是我的实体的 T4 模板,我添加了 [DataContract] 属性以允许对 POCO 进行序列化.
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)#>
<#
这篇关于EF6 POCO INotifyPropertyChanged 没有视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!