How can I seed data in the OnModelCreating method when there's a reference to another entity and none of them have any data?

Viewed 25
modelBuilder.Entity<RoomType>()
                .HasData(
                new RoomType()
                {
                    Id = 1,
                    Title = "Single Room",
                    Description = "A single room has one single bed for single occupancy. An additional bed (called an extra bed) may be added to this room at the request of a guest and charged accordingly.",
                    ImgUrl = "https://webbox.imgix.net/images/owvecfmxulwbfvxm/c56a0c0d-8454-431a-9b3e-f420c72e82e3.jpg?auto=format,compress&fit=crop&crop=entropy",
                    Amenities = Amenities.Where(x => x.Id == 1 && x.Id == 2).ToList()
                },

Amenities and RoomType have a many to many relationship. I have a table called AmenitiesRoomType to facilitate the relationship.

But when I try to seed data in OnModelCreating, I cannot update database.

I get the error:

An attempt was made to use the model while it was being created. A DbContext instance cannot be used inside 'OnModelCreating' in any way that makes use of the model that is being created.

1 Answers

The exception you're getting is related to querying Amenities.Where(x => x.Id == 1 && x.Id == 2).ToList() during the seeding process which isn't possible. You need to seed all three tables separately...


//1. seed RoomType
modelBuilder.Entity<RoomType>()
                .HasData(
                new RoomType()
                {
                    Id = 1,
                    Title = "Single Room",
                    Description = "A single room has one single bed for single occupancy. An additional bed (called an extra bed) may be added to this room at the request of a guest and charged accordingly.",
                    ImgUrl = "https://webbox.imgix.net/images/owvecfmxulwbfvxm/c56a0c0d-8454-431a-9b3e-f420c72e82e3.jpg?auto=format,compress&fit=crop&crop=entropy"
                },

//2. seed Amenity
    //code omitted

//3. seed ManyToMany
modelBuilder.Entity<ManyToMany>()
                .HasData(
                new RoomType()
                {
                    RoomTypeId = 1,
                    AmenityId = 2
                },

Related