在Entity Framework Code First中初始化数据库中的对象

时间:2014-12-25 03:47:38

标签: c# linq ef-code-first initialization entity-framework-6

当我使用它来初始化我的数据库中的对象时,应用程序不会运行:

public class MiradorInitializer : DropCreateDatabaseAlways<MiradorContext>
{
    protected override void Seed(MiradorContext context)
    {
        Client tom = new Client("Tom", "De Backer");
        Booking bookingtom = new Booking("21-02-12", "05-03-12", 450);
        bookingtom.Client = tom;

        Client jeroen = new Client("Jeroen", "De Backer");
        Booking bookingjeroen = new Booking("01-06-13", "16-09-13", 5460);
        bookingjeroen.Client = jeroen;

        context.Bookings.Add(bookingtom);
        context.Bookings.Add(bookingjeroen);
        context.SaveChanges();
    }
}

但是当我在main方法中初始化这些对象和.SaveChanges时它会这样做。我的初始化程序方法有问题吗?

public class Program
{
    private static IEnumerable<Booking> bookings;

    public static void Main(string[] args)
    {
        MiradorContext context = new MiradorContext();
        Client tom = new Client("Tom", "De Backer");
        Booking bookingtom = new Booking("21-02-12", "05-03-12", 450);
        bookingtom.Client = tom;

        Client jeroen = new Client("Jeroen", "De Backer");
        Booking bookingjeroen = new Booking("01-06-13", "16-09-13", 5460);
        bookingjeroen.Client = jeroen;

        context.Bookings.Add(bookingtom);
        context.Bookings.Add(bookingjeroen);
        context.SaveChanges();
        Console.ReadKey();
        readBookings(context);
    }

    public static void readBookings(MiradorContext context)
    {
        Console.WriteLine("\n---Opvragen alle bookings---");
        var bookings = from b in context.Bookings
                       orderby b.Client.Familienaam
                       select b;
        foreach (Booking booking in bookings) { 
            Console.WriteLine(booking.Id + ": " + booking.Client.Familienaam + " " + booking.Client.Voornaam+" - Van "+booking.DatumVan+" tot "+booking.DatumTot+" voor "+booking.Prijs+" euro."); 
        }
        Console.ReadKey();
    }
}

1 个答案:

答案 0 :(得分:0)

在你的MiradorContext类构造函数中,确保你像这样设置初始化器

static MiradorContext()
{
    Database.SetInitializer<MiradorContext>(new MiradorInitializer());
}