Analytic Lunatic
Analytic Lunatic

Reputation: 3944

MVC EntityFramework Code-First Migrations - Seed() Failing with DbUpdateException?

I'm working on a somewhat simple InventoryTracker MVC5 Application wherein I'm having some issues with getting my LocalDatabase to Seed().

When I run the update-database command on my below code, I get an exception as follows on the line context.INV_Types.AddRange(invTypes):

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code. Additional information: An error occurred while updating the entries. See the inner exception for details.

Inner Exception: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.


CODE:

internal sealed class Configuration : DbMigrationsConfiguration<InventoryTracker.DAL.InventoryTrackerContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(InventoryTracker.DAL.InventoryTrackerContext context)
    {
        if (System.Diagnostics.Debugger.IsAttached == false)
        {
            System.Diagnostics.Debugger.Launch();
        }

        List<INV_Locations> invLocs = getLocations();
        context.INV_Locations.AddRange(invLocs);
        List<INV_Manufacturers> invManufacturers = getManufacturers();
        context.INV_Manufacturers.AddRange(invManufacturers);
        List<INV_Models> invModels = getModels();
        context.INV_Models.AddRange(invModels);
        List<INV_Statuses> invStatuses = getStatuses();
        context.INV_Statuses.AddRange(invStatuses);
        List<INV_Types> invTypes = getTypes();
        context.INV_Types.AddRange(invTypes); // EXCEPTION?
        List<INV_Vendors> invVendors = getVendors();
        context.INV_Vendors.AddRange(invVendors);

        context.SaveChanges(); // Was told I needed to Save the other seeds before the Assets to ensure primary keys are created in the other tables?

        List<INV_Assets> invAssets = getAssets();
        context.INV_Assets.AddRange(invAssets);

        context.SaveChanges();
    }

    private List<INV_Types> getTypes()
    {
        List<INV_Types> testTypes = new List<INV_Types>
        {
            new INV_Types
            {
                Id = 1,
                type_description = "Server",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Types
            {
                Id = 2,
                type_description = "IP Phone",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Types
            {
                Id = 3,
                type_description = "Monitor",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testTypes;
    }

    private List<INV_Assets> getAssets()
        {
            List<INV_Assets> testAssets = new List<INV_Assets>
            {
              new INV_Assets
              {
                Id = 1,
                ip_address = "10.10.135.38",
                mac_address = "10.10.177.44",
                note = "",
                owner = "John Smith",
                cost = 35,
                po_number = "G348",
                invoice_number = 1447,
                serial_number = "JX14582Y",
                asset_tag_number = "293548195023",
                //acquired_date = Convert.ToDateTime(10212014),
                acquired_date = DateTime.ParseExact("10212014", "MMddyyyy", CultureInfo.InvariantCulture),
                disposed_date = null,
                created_by = "Admin",
                created_date = DateTime.Now,
                Location_Id = 1,
                Manufacturer_Id = 1,
                Model_Id = 1,
                Status_Id = 2,
                Type_Id = 3,
                Vendor_Id = 3
            }
        };
        return testAssets;
    }

Does anyone have any ideas for what may be causing this in the structure of my Seed() for INV_Types?

I thought it might be something where I needed to save my changes to the context prior to the getTYpes(), but adding context.SaveChanges() after the .AddRange(invStatuses) only results in the same error with that new context.SaveChanges()??

I've included my other seed methods below to help if anyone sees something I am overlooking:

    #region Seed Locations
    private List<INV_Locations> getLocations()
    {
        List<INV_Locations> testLocations = new List<INV_Locations>
        {
            new INV_Locations
            {
                Id = 1,
                location_dept = "IT",
                location_room = "Server",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Locations
            {
                Id = 2,
                location_dept = "Break Room",
                location_room = "Kitchen",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Locations
            {
                Id = 3,
                location_dept = "Accounting",
                location_room = "Conference",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testLocations;
    }
    #endregion

    #region Seed Manufacturers
    private List<INV_Manufacturers> getManufacturers()
    {
        List<INV_Manufacturers> testManufacturers = new List<INV_Manufacturers>
        {
            new INV_Manufacturers
            {
                Id = 1,
                manufacturer_description = "Samsung",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Manufacturers
            {
                Id = 2,
                manufacturer_description = "MITEL",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Manufacturers
            {
                Id = 3,
                manufacturer_description = "Oracle",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testManufacturers;
    }
    #endregion

    #region Seed Models
    private List<INV_Models> getModels()
    {
        List<INV_Models> testModels = new List<INV_Models>
        {
            new INV_Models
            {
                Id = 1,
                model_description = "XTERAV12",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Models
            {
                Id = 2,
                model_description = "5330",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Models
            {
                Id = 3,
                model_description = "Sunblade 6000",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testModels;
    }
    #endregion

    #region Seed Statuses
    private List<INV_Statuses> getStatuses()
    {
        List<INV_Statuses> testStatuses = new List<INV_Statuses>
        {
            new INV_Statuses
            {
                Id = 1,
                status_description = "AVAILABLE",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Statuses
            {
                Id = 2,
                status_description = "SIGNEDOUT",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Statuses
            {
                Id = 3,
                status_description = "RECYCLED",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Statuses
            {
                Id = 4,
                status_description = "AUCTIONED",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testStatuses;
    }
    #endregion

    #region Seed Types
    private List<INV_Types> getTypes()
    {
        List<INV_Types> testTypes = new List<INV_Types>
        {
            new INV_Types
            {
                Id = 1,
                type_description = "Server",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Types
            {
                Id = 2,
                type_description = "IP Phone",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Types
            {
                Id = 3,
                type_description = "Monitor",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testTypes;
    }
    #endregion

    #region Seed Vendors
    private List<INV_Vendors> getVendors()
    {
        List<INV_Vendors> testVendors = new List<INV_Vendors>
        {
            new INV_Vendors
            {
                Id = 1,
                vendor_name = "Oracle",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Vendors
            {
                Id = 2,
                vendor_name = "Centriq",
                created_by = "Admin",
                created_date = DateTime.Now
            },
            new INV_Vendors
            {
                Id = 3,
                vendor_name = "Samsung",
                created_by = "Admin",
                created_date = DateTime.Now
            }
        };
        return testVendors;
    }
    #endregion

EDIT:

As IronMan84 pointed out, I had mistakenly copy-pasted to where I had several instances of each entity with the same Id value (ex. 1, 2, 1 instead of 1, 2, 3). However, the error is still persisting except now at the following line:

        context.INV_Vendors.AddRange(invVendors);

        context.SaveChanges(); // DbUpdateException!

        List<INV_Assets> invAssets = getAssets();

EDIT2: Added the Inner Exception detail to the error originally listed. The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.

EDIT3: To better diagnose the problem, I tried adding context.SaveChanges() after each of the .AddRange() calls, but the very first instance after context.INV_Locations.AddRange(invLocs) results in the same error:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code. Additional information: An error occurred while updating the entries. See the inner exception for details.

Inner Exception: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.

I can only imagine this is referencing my getLocations() setting the [created_date] value to DateTime.Now, but I'm not sure what the issue is?

In my Model I have defined the property as:

    [Required]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime created_date { get; set; }

Upvotes: 0

Views: 1970

Answers (1)

Corey Adler
Corey Adler

Reputation: 16137

2 of the Types in your getTypes() method have an Id value of 1. EF doesn't like that conflict and thus bombs out.

EDIT: The error that you've mentioned in the comments (The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.) is only caused by an object having a DateTime property whose current value is set to a date before January 1, 1753 (most likely it's set to DateTime.MinValue, which is 1/1/0001).

What causes that is that EF maps C#'s DateTime type to SQL's datetime type (as opposed to datetime2, which can go back to 1/1/0001), which has that minimum date requirement mentioned above. When you try to save an object that has a date before 1/1/1753 SQL thinks that you're trying to save a datetime2 in a column that's of type datetime and blows up.

The solution is to debug it and figure out which record(s) have properties that are still set to a bad date (like DateTime.MinValue) and adjust the code to edit those properties accordingly.

Upvotes: 2

Related Questions