EntityFramework种子AddOrUpdate与外键

时间:2013-07-19 21:17:24

标签: c# entity-framework ef-code-first

尝试首先使用Entity Framework和代码在ASP.NET Web应用程序中播种数据。我将此代码放在Configuration.cs文件的Seed()方法中。现在我正在研究解决方案的地址方面,我正在尝试将所有州和县加载到系统中。

这是我的状态代码,工作得很好......

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

如何使用AddOrUpdate()的{​​{1}}功能?这就是我的context.Counties对象的样子。

County

虽然我可以简单地复制我对国家做的格式,但我们知道县名在全国范围内重复使用。所以我不能简单地使用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; } } 作为现有支票。我可以使用name和StateProvinceId字段吗?

2 个答案:

答案 0 :(得分:7)

为什么不将县添加到州,而不是反过来呢?

如果你不能这样做,那么你可以修改你的以下内容:

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

答案 1 :(得分:2)

您必须使用OnModelCreating()方法并声明一个包含县名称和州名缩写的复合键。您还需要县实体上的属性作为缩写。

这是一个带有示例的代码片段:

public class DirectMailDbContext : DbContext, IDirectMailDbContext
{
    public DbSet<BulkQualificationCriteria> QualificationRanges { get; set; }
    public DbSet<CarrierRouteDefinition> RouteDefinitions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new DirectMailDbContextDropInitializer());

        modelBuilder.Entity<BulkQualificationCriteria>().HasKey(q => new {q.QualificationLevel, q.MatchType});  // <- Define composite primary key here
        modelBuilder.Entity<CarrierRouteDefinition>()
                    .HasKey(c => new {c.Zip, c.RouteNumber});

        base.OnModelCreating(modelBuilder);
   }

FROM OP

public class County
{
    public int CountyId { get; set; }
    public int StateProvinceId { get; set; }
    public String Name { get; set; }
    [ScaffoldColumn(false)]
    public String StatePostalAbbreviation { get; set; }

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

SEED

context.Counties.AddOrUpdate(
    c => new {c.StatePostalAbbreviation, c.Name},
    new County { Name = "Aleutians East", StatePostalAbbreviation = "AK" },
    new County { Name = "Aleutians West", StatePostalAbbreviation = "AK" },
    ....
);

OnModelCreating

modelBuilder.Entity<County>().HasKey(q => new { q.Name, q.StatePostalAbbreviation });