Entity Framework 4.1 Code First - Computed/Calcula

2019-07-16 12:23发布

问题:

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.