【问题标题】:Entity Framework Migrations don't include DefaultValue data annotation (EF5RC)实体框架迁移不包括 DefaultValue 数据注释 (EF5RC)
【发布时间】:2012-07-17 18:41:52
【问题描述】:

我有一个如下所示的课程:

[Table("Subscribers", Schema = "gligoran")]
public class Subscriber
{
    [Key]
    public string Email { get; set; }

    [Required]
    [DefaultValue(true)]
    public bool Enabled { get; set; }
}

在创建包含此类的迁移时,我得到:

public partial class AddSubscriberClass : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "gligoran.Subscribers",
            c => new
                {
                    Email = c.String(nullable: false, maxLength: 128),
                    Enabled = c.Boolean(nullable: false),
                })
            .PrimaryKey(t => t.Email);

    }

    public override void Down()
    {
        DropTable("gligoran.Subscribers");
    }
}

我希望Enabled 行看起来像这样:

Enabled = c.Boolean(nullable: false, defaultValue: true),

我当然可以自己做,但我只是想问问有没有办法让 Entity Framework 自动做。

我正在使用最新的 Entity Framework 5 RC (5.0.0-rc.net40)。

【问题讨论】:

    标签: c# entity-framework-migrations entity-framework-5


    【解决方案1】:

    EF 根本不使用 DefaultValue 属性 = 它不是模型的一部分,因此迁移看不到它。您可以在Data UserVoice 上建议支持此注解。

    【讨论】:

    • 我猜手动是唯一的。不过,感谢 UserVoice 链接。我对他们有几个想法。
    • 其实MS今天发布了EF as open source所以你甚至可以自己试试;)
    • 不错!前几天我在找它,得出的结论是它没有开放。我喜欢新的(ish)微软开放政策。
    • 这是一个现有的User Voice suggestion for this feature
    【解决方案2】:

    作为拉迪斯拉夫评论的补充。哪个是对的。你不能在模型中做到这一点。如果您想使用基于代码的迁移。即使用PM commandlet Add-Migration / Update Database,然后这种方法将生成的类引入进程。然后你可以有默认值。请参阅派生自 DBMigrations 的类。见http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigration.addcolumn%28v=vs.103%29.aspx 您可以使用特定的 Column builder lamda 表达式。这允许默认值。

    namespace MigrationsDemo.Migrations
    {
      using System;
      using System.Data.Entity.Migrations;
    
    public partial class SomeClassThatisATable : DbMigration
    {
        public override void Up()
        {
            AddColumn("MyTable", "MyColumn", c => c.String( defaultvalue:"Mydefault"  ));
        }
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      相关资源
      最近更新 更多