使用 db-migration 确定数据库中字段的值范围 [英] Determining the range of value for a field in database by using db-migration

查看:9
本文介绍了使用 db-migration 确定数据库中字段的值范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 Entity Framework 6.x,并通过代码优先的方法生成了我的数据库.创建数据库后,我决定对我的数据库进行一些更改.例如,我想确定模型中 Size 属性的值范围.

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.

我的模特:

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

迁移:

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()
       {
       }
    }
}

推荐答案

Entity Framework 使用 Range 注释指示如何在保存之前验证数据,并由 MVC 生成客户端验证.如果您还希望向数据库添加检查约束,您可以在 Up 迁移中进行:

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

这篇关于使用 db-migration 确定数据库中字段的值范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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