EF Core: how to validate data exists by condition in OnModelCreating

c# ef-core-2.0 entity-framework entity-framework-core seed

Question

I use EF Core and want to add predefined data. It can be done by the following code:

            modelBuilder.Entity<UserPage>().HasData(new UserPage()
            {
                Name = "Homepage",
                Editable = true,
                Path = "path"
            });

this part of code validates whether UserPage object with exactly data exists and if not, creates it But I want to add new record only when record with Name = "Homepage" does not exist, otherwise no. Code above will add new record even if record with name "Homepage" already exists, but Editable = false for example. I want to validate it, I try:

        if (UserPages.Where(p => p.Name.Equals("Homepage", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() == null)
        {
            modelBuilder.Entity<UserPage>().HasData(new UserPage()
            {
                Name = "Homepage",
                Editable = true,
                Path = "path"
            });
        }

but I get an 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
1
7/25/2019 11:35:13 AM

Accepted Answer

That is outside the context of "database seeding". Seeding "makes sure" data exists as you specify it when the database is being created/updated and it's to be done at "migration time", when you may not have a database configured at all (at the point that code is executing, you are defining the model to EF: you may not even have a ready real database to query data from: that's the error you are seeing).

If what you are after is handling some logic on the database itself, and not at "database design time", then don't do it on the model creation, and run that logic when your app starts (or at any other point in time), after the database is created and seeded .

2
7/25/2019 11:45:49 AM


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