简体   繁体   中英

EF Code First Exception on non-nullable POCO property

I have a POCO that can't have any nullable properties, for various reasons, but the database I'm connecting to has null values for some of these corresponding properties, so I have to handle these and set them to something else in the property getter/setter logic. But I'm still getting...

Constraint Exception was unhandled by user code: The 'DischargeDate' property on 'Visits' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.DateTime'.

...Here's my property logic....

 public class Visits
    {
        private DateTime _dischargeDate;
public DateTime DischargeDate
        {
            get {
                if (this._dischargeDate == null)
                {
                    this._dischargeDate = DateTime.MinValue;
                    return this._dischargeDate;
                }
                else
                {
                    return this._dischargeDate;
                }
            }
            set
            {
                if (value == null)
                {
                    this._dischargeDate = DateTime.MinValue;
                }
                else
                {
                    this._dischargeDate = value;
                }
            }
}

...and the DbContext is just straight forward, like...

public class MyDBContext : DbContext
    {
        public MyDBContext(string connection)
            : base(connection)
        {
        }

        public DbSet<Visits> Visits { get; set; }
}

I have no idea why I'm getting this error. It throws when the context is loaded. Or to be more specific, when I try to access the DbSet<Visit> Visits, like _dbcontext.Visits;

DateTime can't be null. So even though your setter is checking for null (which I'm surprised that comparison even passes), a property of DateTime cannot be set to null. So that's why EF is throwing that error and thus that logic won't work.

If the database is going to have nulls in it, you need your POCOs to have DateTime? as their property type so that EF can set it to null.

Simply doing:

public class Visits
{
    private DateTime _dischargeDate;

    public DateTime? DischargeDate
    {
        get {
            return _dischargeDate;
        }
        set
        {
            if (value == null)
            {
                this._dischargeDate = DateTime.MinValue;
            }
            else
            {
                this._dischargeDate = value.Value;
            }
        }
    }
}

would work - _dischargeDate would never be null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM