Reputation: 734
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.
Upvotes: 5
Views: 5193
Reputation: 236328
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. I.e. 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.
Upvotes: 2
Reputation: 1987
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; }
}
Upvotes: 2
Reputation: 62318
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.
Upvotes: 1