I have the following model:
class RentOrder
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
How can I add constraint in Entity Framework Code First that StartD开发者_开发技巧ate
must be always less than EndDate
? The only way I know is to add it by executing SQL-command in overridden Seed
method. Is there more simple way, without SQL?
The only way to solve this problem now, as I mentioned in question, is to write SQL-commands in Seed
method:
public class MyDatabaseInitializer : DropCreateDatabaseAlways<MyDatabaseContext>
{
protected override void Seed(MyDatabaseContext context)
{
context.Database.ExecuteSqlCommand(@"ALTER TABLE Orders
ADD CONSTRAINT C_Dates CHECK(EndDate > StartDate)");
}
}
And call somewhere on the application start:
Database.SetInitializer(new MyDatabaseInitializer());
You can implement the set method and throw a custom exception if the enddate is less then the start date.
You would need to implement it in both because you would still be able to set the opposite. Here is a quick example (assuming the start and end date cannot be the same day):
class RentOrder
{
public DateTime StartDate
{
get { return _startDate };
set
{
if (value >= _endDate)
throw new Exception("Start Date cannot be greater than End Date");
_startDate = value;
};
}
private DateTime _startDate;
public DateTime EndDate
{
get { return _endDate};
set
{
if (value <= _startDate)
throw new Exception("End Date cannot be less than Start Date");
_endDate = value;
};
}
private DateTime _endDate;
}
精彩评论