Entity Framework 4.1 Code First - Computed/Calculated column not being inserted

自作多情 提交于 2019-12-12 18:39:34

问题


I have below entity with a calculated/computed column:

public EntityA
{
    [Key(), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    .....

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public virtual string RefId {
        get
        {
            return this.Id.ToString().PadLeft(7, '0');
        }

        private set
        {
        }
    }
} 

RefId is a computed column that depends on the Id value.

After performing commit changes to database with SaveChanges I can check that Id and RefId have been set correctly for the entity I am currently inserting on database, but If I open the database and check RefId column for this entity, I can observe that RefId column has not been set, if figures as NULL. Why? Any ideas?


回答1:


DatabaseGeneratedOption.Computed means that's the value is computed by the database engine. So EF will never update this value, only read from the db.

So if you want this value in the db: - remove DatabaseGeneratedOption.Computed and set the value in your code, or - set a computed column at database engine side.

Otherwise you should set RefId as not mapped. But in this case you will have no column in the db.



来源:https://stackoverflow.com/questions/16981259/entity-framework-4-1-code-first-computed-calculated-column-not-being-inserted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!