简体   繁体   中英

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; 1, 2 or 3. Otherwise EF will throw exception.

I can make a Status table and define all statuses of course. 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 . 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.

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 . In SQL you would alter table this way

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

It's not currently supported by EF directly. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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