实体框架 4.1 持久化 getter
很多人喜欢 EF4.1,但一直坚持这样做!
我希望最终得到一个这样的类,其中 EF 处理这两个属性,并且它们都在数据库中。
public class myClass
{
public int priority { get; set; }
public string status { get { return priority > 10 ? "Low" : "High" } }
}
1)当我从数据库生成模型时,我需要以某种方式将状态计算注入到其属性中。
2)希望当我从数据库重新生成模型时该解决方案能够发挥作用。
Lots of Like for EF4.1, but have got stuck on doing this!
I want to end up with a class like this, where EF handles both properties, and they are both in the database.
public class myClass
{
public int priority { get; set; }
public string status { get { return priority > 10 ? "Low" : "High" } }
}
1) When I generate the model from the database, I need to somehow inject the status calculation into its property.
2) Hopefully the solution works when I regenerate my model from the database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法保留此类属性。它是业务逻辑(计算属性)。如果你想保存它,属性必须有 setter,因为 EF 会在具体化从数据库加载的实体时尝试设置它,但一旦你暴露了 setter,你的 getter 将失去意义,并且该逻辑将不得不移至其他地方。
编辑:
解决方法是将您的
Status
逻辑包装到帮助程序扩展方法中:现在您可以在查询中使用它,如下所示:
You cannot persist such property. It is business logic (computed property). If you want to save it the property must have setter because EF will try to set it when materializing entity loaded from the database but once you expose a setter your getter will not make sense and this logic will have to be moved elsewhere.
Edit:
The workaround is to wrap your
Status
logic into helper extension method:Now you can use it in the query like: