实体框架4.1代码第一 - 计算/计算列未插入 [英] Entity Framework 4.1 Code First - Computed/Calculated column not being inserted

查看:159
本文介绍了实体框架4.1代码第一 - 计算/计算列未插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计算/计算列的实体:

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是依赖于Id值的计算列。

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

使用SaveChanges I执行对数据库的提交更改后可以检查我正在数据库中插入的实体的Id和RefId是否正确设置,但是如果我打开数据库并检查该实体的RefId列,我可以看到,如果数字为NULL,则RefId列尚未设置。为什么?任何想法?

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?

推荐答案

DatabaseGeneratedOption.Computed 意味着该值被计算由数据库引擎。所以EF永远不会更新这个值,只能从数据库读取。

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.

所以如果你想在db中的这个值:
- 删除 DatabaseGeneratedOption.Computed 并设置代码中的值,或
- 在数据库引擎端设置一个计算列。

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.

否则您应该将RefId设置为未映射。但是在这种情况下,您将不会在db中找到任何列。

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

这篇关于实体框架4.1代码第一 - 计算/计算列未插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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