如何首先在EF代码中创建持久化的计算列? [英] How to make persisted computed column in EF code first?

查看:96
本文介绍了如何首先在EF代码中创建持久化的计算列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使此列与数据库中的 PERSISTED COMPUTED列相似?

How do I get this column as similar to a PERSISTED COMPUTED column in the database?

我当前的尝试(它将所有CompCol行加载为null种子):

    public class Call
    {
        public Call()
        {
        }

        [Key]
        public int Id { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public string CompCol
        {
            get
            {
                return "ABC-" + Convert.ToString(Id).PadLeft(5, '0');
            }
            protected set {}
        }
}


推荐答案

我找到的解决方案是:


  1. 确保已启用自动迁移关。这样一来,VS便可以生成脚本(流利的api代码)供我们进一步自定义,而不仅仅是运行它。因此,在配置类中:

  1. Make sure auto migrations are turned off. This is so that VS will generate a script (fluent api code) for us to further customise instead of just running it. So in the configuration class :

public Configuration()
{
    AutomaticMigrationsEnabled = false;
}


  • 将字段添加到类中并按如下方式进行设置,则setter是私有的,因为我们显然无法写入计算字段:

  • Add the field to the class and set it as computed like so, the setter is private because we obviously cannot write to a computed field :

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string BreakdownNo { get; private set; }
    


  • 然后执行 add-migration [xyz-name] 在Package Manager控制台中生成迁移代码,该代码将以给定名称显示在migrations文件夹下。

  • Then do an add-migration [xyz-name] in the Package Manager Console to generate the migration code, which will appear under the migrations folder with the given name.

    迁移注释掉 Up()中的代码,并添加自定义SQL,如下所示:

    Inside the migration comment out the code in Up() and add custom SQL like so :

    public override void Up()
    {
        //AddColumn("dbo.Calls", "BreakdownNo", c => c.String());
        Sql("ALTER TABLE dbo.Calls ADD BreakdownNo AS ('BD'+RIGHT('00000'+ CAST(Id AS VARCHAR), 6))");
    }
    


  • 执行更新数据库在PM中,它应该正确添加计算列。

  • Do an update-database in the PM and it should add the computed column properly.

    更多说明:如果公式错误,则必须通过执行 update-database -targetMigration:[迁移名称返回] 来还原迁移。然后再使用另一个 add-migration名称并在此处修改公式,最后以update-database结束。也许有更好的方法,但这是我发现和使用的方法。

    FURTHER NOTES : If you get the formula wrong then you will have to revert back the migration by doing an update-database -targetMigration: [name of migration to go back to] then do another add-migration name and amend your formula there, finishing off with update-database. There may be a better way but this is what I found and used.

    但是我还没有找到使该字段持久化的方法。

    I did not however find a way to make the field persisted yet.

    这篇关于如何首先在EF代码中创建持久化的计算列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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