简体   繁体   中英

How to enforce new data integrity rules in Entity Framework

I've got a table that has had a few new columns added, and they allow nulls to accurately accommodate the existing data. At the time those records were created the new columns did not exist, so a null accurately represents the state of the database at that time. For all new data I don't want to allow nulls. What is the best practice to manage that?

If I use .IsRequired() in the EntityTypeConfiguration class it will try to alter the table to make the column non-nullable and fail when it encounters the historic nulls. I still want to be able to read those old records, I just don't want to write any new records without the new column.

I want to do this as close to the DB as possible, so I've put some validation code in the setter.

    private string _CountryCode;
    public string CountryCode
    {
        get
        {
            return _CountryCode;
        }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentException("Country Code Required");
            _CountryCode = value;
        }
    }

This does work, but I have a nagging feeling there is a cleaner solution out there.

Does the answer to this question " Default value for Required fields in Entity Framework migrations? " help you?

You have to define a defaultValueSql so all the NULL values can become required.

The proper approach would be using IsRequired() because for EF, it either is Required, or it isn't. If it somehow is acceptable not to be there, it is exactly that: not Required.

The way to handle it for me would be to migrate previous data, but if you decide not to do that, your solution seems a good approach to handle it, however, your current setter looks really weird to me. For example, if I instantiate the class, and do myObject.CountryCode = "AA"; , I'd get an exception because the current value, before my set, is null or blank. Sounds erroneous. Maybe you should test value instead?

On a side note, most of the corporate systems I've seen using EF would prevent EF from automatically altering the database. It's common (but not universal) practice to use Database.SetInitializer<YourContextClass>(null); in your DbContext to prevent it from doing so automatically, in your production environment. You still can call the methods to force an update to the database structure under certain circumstances, or use dacpacs generated by database projects.

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