In Entity Framework Code First, how should I access a calculated column?

c# ef-code-first entity-framework


In my ASP.NET MVC application, Entity Framework Code First is used. There are many columns in one of my courses that are combined. By executing an edit table script in the database initializer, I am placing these fields in the tables as calculated columns. Say the class is made up of:

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

The modify script looks like this:

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

I desire theTotal Sources column must be seen in the online application. What's the most effective technique to do this? The[DatabaseGenerated(DatabaseGeneratedOption.Computed)] Because EF Code First generates the table from the class before the change script is executed, attribute is ineffective.

Any advice is appreciated.

8/4/2011 4:16:57 PM

Accepted Answer

I do have a workaround, kind of.

Calculated fields may only be used on databases that already exist.

If your property is added to a CF object as:

public decimal TotalSources { get; set; }

Additionally, if you include a line in your script that purges data related to the creation of that database:

DELETE FROM [dbo].[EdmMetadata]

I just tested that, and according to CF, it will work if the database is already there.

UPDATE I failed to mention that if you add property to your Bond object in this way, you must change it in your script so that it is computed rather than added: When everything is functioning without this column, you may manually "synchronize" the database and model by adding it to the model as computed and the table as calculated. When the hash is removed from the edm metadata table, CF will function without attempting to recreate the model using the database.

8/13/2011 3:37:50 PM

Popular Answer

This is defining, certainly not in favor.Computed A custom property option will raise an error. logic first Equals code first. Use the database first if you require custom calculated properties. Only the identification column and timestamp are supported by code initially for database logic.

The issue is that you need the column to be designated as calculated, but doing so during database creation is not possible. If the column is not designated as calculated, EF will produce update statements that attempt to update the column but fail in the database.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow