How to extend Entity from EF?
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?
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).
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.
精彩评论