Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Nullable type Code First

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.

like image 548
Cuong Nguyen Avatar asked Aug 04 '26 06:08

Cuong Nguyen


2 Answers

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; }
}
like image 198
Leniel Maccaferri Avatar answered Aug 05 '26 18:08

Leniel Maccaferri


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();
    }
}
like image 39
Vahid Hassani Avatar answered Aug 05 '26 18:08

Vahid Hassani