实体框架代码优先计算属性
我在 ASP.NET MVC 3 Web 应用程序中使用实体框架“代码优先”方法。在我的数据库中,我有几个计算列。我需要使用这些列来显示数据(效果很好)。
但是,当我向该表中插入行时,出现以下错误:
“ChargePointText”列不能 修改过,因为它是 计算列或者是一个的结果 UNION 运算符。
有没有办法在我的班级中将属性标记为只读?
public class Tariff
{
public int TariffId { get; set; }
public int Seq { get; set; }
public int TariffType { get; set; }
public int TariffValue { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int ChargePoint { get; set; }
public string ChargePointText { get; set; }
}
I'm using Entity Framework "Code First" approach in a ASP.NET MVC 3 web application. In my database I have several computed columns. I need to use these columns to display data (which works fine).
However when I come to insert rows into this table, I'm getting the following error:
The column "ChargePointText" cannot be
modified because it is either a
computed column or is the result of a
UNION operator.
Is there a way to mark the property as readonly in my class?
public class Tariff
{
public int TariffId { get; set; }
public int Seq { get; set; }
public int TariffType { get; set; }
public int TariffValue { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int ChargePoint { get; set; }
public string ChargePointText { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了解决方案。实体框架提供了一个名为 DatabaseGenelated 的数据注释。像这样使用它:
在此处获取更多详细信息:http://msdn.microsoft.com/en-us/库/gg193958.aspx
I've found the solution. Entity Framework provides a data annotation called DatabaseGenerated. Use it like this:
Get more details here: http://msdn.microsoft.com/en-us/library/gg193958.aspx
还有其他一些选择。
第一个是将映射文件中的属性设置从:
更改为:
这与 Same Huggill 的解决方案几乎相同,只是它将此配置保留在映射中,而不是模型中。我觉得这稍微好一些,因为映射类已经包含告诉实体框架如何加载该类型实体的代码,因此计算字段的知识属于其中。
另一个选项是
NotMappedAttribute
,它可以应用于实体的各个属性,如下所示:当实体包含未从数据库填充的属性时,这非常有用,但它在OP 面临的场景,即 EF 不会尝试将值推送到用
NotMappedAttribute
标记的属性中,因此插入应该可以工作。There are a couple of other options as well.
The first is to change the property setup in the mapping file from:
to:
This is pretty much the same as Same Huggill's solution, except it keeps this configuration in the mapping, rather than in the model. I feel this is slightly better since the mapping class already contains code to tell Entity Framework how to load that type of entity, so the knowledge that a field is computed belongs in there.
Another option is the
NotMappedAttribute
which can be applied to individual properties of an entity like so:This is useful for when the entity contains properties that are not populated from the database, but it should be equally useful in the scenario faced by OP, i.e., EF will not try to push the value in a property marked with the
NotMappedAttribute
, therefore insert should work.