Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 410
ahmet Avatar asked Jan 27 '17 12:01

ahmet


1 Answers

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.

like image 145
Igor Avatar answered Sep 21 '22 10:09

Igor