简体   繁体   English

有没有办法限制实体框架中的列的值?

[英]Is there a way to restrict value of a column in Entity Framework?

I want to restrict values of a property of an entity in Entity Framework. 我想限制实体框架中实体的属性值。

For example: 例如:

public class Position: EntityBase
{
    [AnAtribute("Values:1,2,3")]
    public int Status { get; set; }
    public string ReferenceCode { get; set; }
    public string Location { get; set; }
    public string Content { get; set; }
}

Values can come from an enum also. 值也可以来自枚举。

In this table here, the Status column can have a value; 在此表中,“ Status列可以具有值; 1, 2 or 3. Otherwise EF will throw exception. 1,2或3.否则EF会抛出异常。

I can make a Status table and define all statuses of course. 我可以制作Status表并定义所有状态。 But I don't want to join with that table everytime. 但我不想每次都加入那张桌子。 So it is not an option. 所以这不是一个选择。

I tried this and it works .While saving to Db it gives me validation error as well . 我试过这个并且它可以工作。虽然保存到Db它也给我验证错误。 Please check if this is useful. 请检查这是否有用。

 public class RangeTest
{
    [Key]
    [Range(1, 3)]
    public int ProjectId { get; set; }

}

在此输入图像描述

Make the property an Enum and define that enum. 使属性为Enum并定义该枚举。

public enum Status
{
  SomeStatusA = 1,
  SomeStatusB = 2,
  SomeStatusC = 3,
}
public class Position: EntityBase
{
   public Status Status { get; set; }
   public string ReferenceCode { get; set; }
   public string Location { get; set; }
   public string Content { get; set; }
}

You can also add a foreign key constraint on the Status table (you mentioned you have one) which would prevent you from adding/updating a status value that is out of range when it hits the database. 您还可以在状态表(您提到有一个)上添加外键约束 ,这会阻止您在命中数据库时添加/更新超出范围的状态值。

What you need is CHECK CONSTRAINT . 你需要的是CHECK CONSTRAINT In SQL you would alter table this way 在SQL中,您可以通过这种方式更改表

ALTER TABLE Position
   ADD CONSTRAINT CK_Position_Status CHECK (Status IN (1, 2, 3))

It's not currently supported by EF directly. EF目前不支持。 Ie there is no some attribute or configuration which allows you generate table with check constraint or alter existing table. 即没有一些属性或配置允许您生成具有检查约束的表或更改现有表。 But you can add such constraint manually in migration: 但您可以在迁移中手动添加此类约束:

migrationBuilder.Sql(@"ALTER TABLE Position
     ADD CONSTRAINT CK_Position_Status CHECK (Status IN (1, 2, 3))");

Also I would recommend you to use enum instead of integer for Status field (if it is possible). 另外我建议您使用枚举而不是整数作为状态字段(如果可能的话)。 Thus nobody will 'guess' which values supposed to be valid and which are not. 因此,没有人会“猜测”哪些值应该是有效的,哪些值不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM