How to extend Entity from EF?

孤街浪徒 提交于 2019-12-22 12:37:35

问题


All entity created by EF is partial class. so it is extendable. Suppose I have entity Person like

partial class Person{FirstName, LastName, .....}

Then I want to add a compute property Name like:

partial class Person{

[DataMember]        
public string Name
{
   get { return String.Format("{0} {1}", this.FirstName, this.LastName); }
}

partial void OnFirstNameChanged()
{
  //.....
  this.ReportPropertyChanged("Name");
}

partial void OnLastNameChanged()
{
  //.....
  this.ReportPropertyChanged("Name");
}
//....
}

Then for data upate operation I got following error: The property 'Name' does not have a valid entity mapping on the entity object. For more information, see the Entity Framework documentation.

How to fix this solution?


回答1:


The problem is with those ReportPropertyChanged("Name"), you are reporting to ObjectStateManager that the "Name" property has been changed, while this property does not exists in your model metadata (it has just been declared in your partial class, ObjectContext and ObjectStateManager do not know anything about this property).
If you add those OnLastNameChanged and OnFirstNameChanged partial methods, just get rid of them, you don't need them.




回答2:


I've just had the same error. Do not use "ReportPropertyChanged()" but "OnPropertyChanged()" instead. There you go.

ReportPropertyChanged() only works for real entity objects (like FirstName and LastName that are e.g. real database fields), but not those computed ones (like Name, which only exists in your partial class).



来源:https://stackoverflow.com/questions/4046349/how-to-extend-entity-from-ef

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