EntityFramework Seed AddOrUpdate with Foreign Key

c# ef-code-first entity-framework

Question

Trying to seed data in an ASP.NET web app utilizing Entity Framework and code first. I'm placing this code in the Seed() method of the Configuration.cs file. Right now I'm working on the address aspects of the solution and I'm trying to get all of the states and counties loaded into the system.

Here is my code for states, working just fine...

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

How can I go about using the AddOrUpdate() function for context.Counties? This is what my County object looks like.

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; }
}

While I can simply duplicate the format for what I did with States, we know that counties names are reused throughout the country. So I can't simply use c => c.Name as the existing check. I could use the name and StateProvinceId field though?

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

Popular Answer

Why not add the counties to the states, instead of doing it in reverse?

If you can't do that, then you can modify 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