EntityFramework Seed AddOrUpdate with Foreign Key

c# ef-code-first entity-framework

Question

attempting to use code first and Entity Framework to seed data into an ASP.NET web application. This code is being added to theSeed() the Configuration.cs file's method. I'm currently working on the solution's address-related components and trying to load every state and county into the system.

Here is my perfectly functional state-specific code.

context.StateProvinces.AddOrUpdate(
    p => p.Abbreviation,
    new StateProvince { Abbreviation = "AL", Name = "Alabama" },
    new StateProvince { Abbreviation = "AK", Name = "Alaska" },
    new StateProvince { Abbreviation = "AZ", Name = "Arizona" },
    ....
);

What steps must I take to use theAddOrUpdate() perform forcontext.Counties ? Here's what myCounty item appears to be.

public class County
{
    public int CountyId { get; set; }
    public int StateProvinceId { get; set; }
    public String Name { get; set; }

    [ForeignKey("StateProvinceId")]
    public virtual StateProvince StateProvince { get; set; }
}

Although I may simply copy the format from what I did with the States, we know that county names are frequently utilized across the nation. I therefore can't just usec => c.Name like the current check. However, I could make use of the name and StateProvinceId fields.

1
9
1/6/2014 8:14:57 PM

Popular Answer

Instead of going backwards, why not add the counties to the states?

If you are unable to do so, you can change yours to the following:

var al = new StateProvince { Abbreviation = "AL", Name = "Alabama" },
var ak = new StateProvince { Abbreviation = "AK", Name = "Alaska" },
var ar = new StateProvince { Abbreviation = "AZ", Name = "Arizona" },

context.StateProvinces.AddOrUpdate(
    p => p.Abbreviation,
    al,
    ak,
    ar
);

context.SaveChanges();

context.Counties.Add(new County() { Name = "Something", StateProvince = al });

// DONT CALL SAVE, Initializer needs something to do or it complains
8
7/19/2013 9:29:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow