我应该如何在实体框架code首先访问一个计算列? [英] How should I access a computed column in Entity Framework Code First?

查看:127
本文介绍了我应该如何在实体框架code首先访问一个计算列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架code首先在我的ASP.NET MVC应用程序。我的一个班有加在一起的多个列。我通过在数据库初始化运行ALTER TABLE脚本存储这些列如表中计算列。比方说,类是这样的:

I am using Entity Framework Code First in my ASP.NET MVC application. One of my classes has several columns that are added together. I am storing these columns as computed columns in the tables by running an alter table script in the database initializer. Let's say the class looks like:

public class Bond
{
        public decimal ParAmountOfIssuance { get; set; }
        public decimal AccruedInterest { get; set; }
        public decimal Premium { get; set; }
        public decimal OriginalIssueDiscount { get; set; }
}

在ALTER脚本是这样的:

The alter script is something like:

alter table Bonds
add TotalSources as (ParAmountOfIssuance + AccruedInterest + Premium - OriginalIssueDiscount)

我要的来源总计列可用于查看Web应用程序。什么是实现这一目标的最佳途径?在 [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 属性不起作用,因为EF code首先创建一个从ALTER脚本运行前级表。

I want the Total Sources column to be available for viewing in the web app. What's the best way to accomplish this? The [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute doesn't work because EF Code First creates the table from the class before the alter script is ran.

任何建议都欢迎。

推荐答案

我有一个解决办法颇有几分。

I have a somewhat of an workaround.

您只能使用计算领域的现有数据库上。

You can only use calculated field on a existing database.

如果您的属性添加到CF对象:

If you add your property to CF object as:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public decimal TotalSources { get; set; }

如果你添加在脚本中的电话线将删除有关代该数据库的信息:

and if you add a line in your script that will delete information about generation of that database:

DELETE FROM [dbo].[EdmMetadata]

CF会假设它是现有的数据库,它会工作,我刚才试过了。

CF will assume it is existing database and it will work, I have just tried.

更新我忘了,如果你添加属性你这样的债券实体,那么在你的脚本,你需要改变它,使其计算的,不加吧:)
你甚至可以手工同步的数据库和模型 - 在您所拥有的一切工作没有这个场点,在模型中添加的计算,并且在表作为计算。当您从EDM元数据表删除哈希CF将工作,但不尝试重新生成数据库模型。

UPDATE I forgot, if you add property to your Bond entity like this, then in your script you need to alter it to make it calculated, not add it :) You can even manually "synchronize" database and model - at point where you have everything working without this field, add it in model as computed, and in table as calculated. When you delete hash from edm metadata table CF will work without trying to regenerate model with database.

这篇关于我应该如何在实体框架code首先访问一个计算列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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