我有一个名为Account的EF 5实体,使用标准模板生成。
它有一个属性AccountTypeId。
当它发生变化时,我需要通知,以便更新另一个字段。
这通常如何做?这只需要一个属性,因此我不想使用修改后的模板。
AccountTypeId绑定到WinForms中UI中的ComboBox,因此它不像我在WPF中通常那样真正的MVVM应用程序。
答案 0 :(得分:2)
一种方法是转到EDMX并将字段重命名为AccountTypeID_Internal(例如),并在EDMX中将属性设置为Private
。然后创建一个Partial Class。
生成的Account.cs应如下所示:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace <yournamespace>
{
using System;
using System.Collections.Generic;
public partial class Account
{
private int AccountTypeId_Internal { get; set; }
// other auto generated properties
}
}
Account.Partial.Cs
public partial class Account : INotifyPropertyChanged
{
public Int AccountTypeId
{
get
{
return this.AccountTypeId_Internal;
}
set
{
this.AccountTypeId_Internal = value;
// Do INotifyPropertyChangedLogic
}
}
// Implement INotifyPropertyChanged
}
这样做的好处是你已编写的代码根本不需要改变。缺点是,如果从edmx中删除Accout并重新添加它,则必须再次执行edmx步骤。
答案 1 :(得分:2)
您可以使用名为PropertyChanged.Fody的NuGet包使用几行代码执行此操作。包文档位于GitHub。请参阅我的CodeProject提示"Adding INotifyPropertyChanged to Entity Framework Classes&#34;。
我应该指出,该技术将为类中的每个属性实现INPC。如果您只想要INPC用于单个属性并且您不想修改T4模板或EDMX文件,那么您可以利用以下事实:使用&#34; partial&#34;生成实体类。关键字,允许您添加&#34;包装&#34;属于Erik Philips描述的单独(非生成)文件中的属性。您必须修改现有代码以引用包装器属性,但重新生成模型或实体时不会中断任何内容。