Determining the range of value for a field in database by using db-migration

点点圈 提交于 2019-12-04 06:13:55

问题


I've used Entity Framework 6.x and I've produced my database by code-first approach. After creating db, I've decided to some changes in my db. for example I want to determine a range of value for Size property in my model.

my model:

public class Tag : Entity, ITag
{
    /// <summary>
    /// Size can be 1, 2, 3 or 4
    /// </summary>
    [Range(1, 4)]
    public virtual int Size { get; set; }

    [Required]
    [StringLength(25)]
    public virtual string Title { get; set; }

    [StringLength(256)]
    public virtual string Description { get; set; }

    public virtual bool IsActive { get; set; }

    public virtual ISet<ArticleTag> ArticleTags { get; set; }

    public virtual ISet<ProjectTag> ProjectTags { get; set; }
}

Migration:

namespace Jahan.Blog.Web.Mvc.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Initial : DbMigration
    {
       public override void Up()
       {
           // I want to write some code like this that can provide rage of data. 1 to 4:
           //AlterColumn("dbo.Tag", "Size", c => c.Int(nullable: false,defaultValue:1));
           //... but I don't know how can I do it.
       }

       public override void Down()
       {
       }
    }
}

回答1:


The Range annotation is used by the Entity Framework to indicate how to validate the data prior to saving, and by MVC to generate client side validation. If you also wish to add a check constraint to the database you can do it in your Up migration:

    public override void Up()
    {
        //Sql to add a check constraint using Sql Server syntax:
        Sql(@"ALTER Table dbo.Tags 
        ADD CONSTRAINT chk_Size 
        CHECK (Size IN (1, 2, 3, 4))");
    }


来源:https://stackoverflow.com/questions/26493019/determining-the-range-of-value-for-a-field-in-database-by-using-db-migration

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