EF 4.1 SeedData没有填充表格

时间:2012-01-30 19:38:46

标签: asp.net-mvc-3 entity-framework-4

我创建了一个SeedData类,并使用我想要填充到表中的值填充它。当我运行应用程序时,我没有收到任何错误,但表中没有填充种子数据。

我正在使用ASP.NET MVC3和EF 4.1

我尝试过DropCreateDatabaseAlways和DropCreateIfModelChanges没有运气

在Global ASAX中,我在Application_Start

中有以下链接
System.Data.Entity.Database.SetInitializer(new EDWv2.Models.SeedData());

我的SeedData类定义如下:

public class SeedData : DropCreateDatabaseAlways<EDWContext>
{
    protected override void Seed(EDWContext context)
    {

        var controlsystemdesignation = new List<ControlSystemDesignation>
        {
            new ControlSystemDesignation { Name = "BA"},
            new ControlSystemDesignation { Name = "BP"},
            new ControlSystemDesignation { Name = "RA"},
            new ControlSystemDesignation { Name = "GA"},
            new ControlSystemDesignation { Name = "WA"},
            new ControlSystemDesignation { Name = "WB"},
            new ControlSystemDesignation { Name = "WC"},
            new ControlSystemDesignation { Name = "EA"},
            new ControlSystemDesignation { Name = "EB"},
            new ControlSystemDesignation { Name = "EC"},
            new ControlSystemDesignation { Name = "DA"},
            new ControlSystemDesignation { Name = "DB"},
            new ControlSystemDesignation { Name = "DC"},
            new ControlSystemDesignation { Name = "FA"},
            new ControlSystemDesignation { Name = "FB"},
            new ControlSystemDesignation { Name = "SA"},
            new ControlSystemDesignation { Name = "SB"},
            new ControlSystemDesignation { Name = "SC"},
            new ControlSystemDesignation { Name = "LA"},
            new ControlSystemDesignation { Name = "LD"},
            new ControlSystemDesignation { Name = "DP"},
            new ControlSystemDesignation { Name = "PA"},
            new ControlSystemDesignation { Name = "PB"},
            new ControlSystemDesignation { Name = "PC"},
            new ControlSystemDesignation { Name = "UL"},
            new ControlSystemDesignation { Name = "UA"}
    };
        base.Seed(context);
        context.SaveChanges();
    }
}

谢谢,

杰森

2 个答案:

答案 0 :(得分:2)

您需要将ControlSystemDesignation个实体添加到context

public class SeedData : DropCreateDatabaseAlways<EDWContext>
{
    protected override void Seed(EDWContext context)
    {

        var controlsystemdesignation = new List<ControlSystemDesignation>
        {
            new ControlSystemDesignation { Name = "BA"},
            new ControlSystemDesignation { Name = "BP"},
            new ControlSystemDesignation { Name = "RA"},
            new ControlSystemDesignation { Name = "GA"}
            //...
        };

        controlsystemdesignation.ForEach(item => context.ControlSystemDesignations.Add(item));

        context.SaveChanges();
    }
}

答案 1 :(得分:0)

您需要将这些实例添加到DbSet<ControlSystemDesignation>,这应该是您的上下文的一部分。

context.ControlSystemDesignations.Add(instance);