How should I access a computed column in Entity Framework Code First?

前端 未结 3 715
野的像风
野的像风 2020-12-03 08:40

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 c

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 09:13

    I have a somewhat of an workaround.

    You can only use calculated field on a existing database.

    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 will assume it is existing database and it will work, I have just tried.

    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.

提交回复
热议问题