如何从EF扩展实体? [英] How to extend Entity from EF?

查看:116
本文介绍了如何从EF扩展实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由EF创建的所有实体都是部分类。所以它是可扩展的。假设我有实体Person像

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.

如何解决此问题?

推荐答案

问题在于这些 ReportPropertyChanged(Name),您将向ObjectStateManager 报告Name属性具有已被更改,而您的模型元数据中不存在此属性(刚刚在您的部分类中声明了 ObjectContext ObjectStateManager 不了解此属性的任何内容)。


如果您添加了 OnLastNameChanged OnFirstNameChanged 部分方法,只是摆脱他们,你不需要他们。

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.

这篇关于如何从EF扩展实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆