I have my project run just fine using EF Code First. But now I need to add 1 more field into DB(e.g CreateDate of type DateTime) which can be null.
So, I wrote script to add 1 more field to DB(CreateDate (datetime) null), then I modified my model to include new field
public class Account()
{
...
public DateTime CreateDate { get; set; }
}
And below is the code to make this field option using FluentApi
Property(x => x.CreateDate).IsOptional();
The problem is when I tried to get any instance of Account, I got an error When I modify the field as follow:
public DateTime? CreateDate { get; set; }
then it works.
Can you guys please explain to me about this? Why doesn't my fluent api work or did I do something wrong?
Thank you.
You already gave the solution in your question... :) You must declare the new property as:
public DateTime? CreateDate { get; set; }
DateTime? is a nullable type and means that CreateDate can be null.
This is necessary because when a record is brought from the database and its CreateDate is NULL the backing property on your model should accept null as a possible value. If you declare the property as just DateTime CreateDate the framework gives you the error to inform that it could not assign the NULL value to a property that doesn't accept NULL.
So you should have:
public class Account()
{
...
public DateTime? CreateDate { get; set; }
}
Try based on this example:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public string Phone { get; set; }
public DateTime Birthday { get; set; }
}
DbContext and fluent Api:
public class dbMvc1:DbContext
{
public DbSet<Student> Student { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().Property(x => x.Birthday).IsOptional();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With