Determining the range of value for a field in data

2019-03-03 17:46发布

问题:

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))");
    }