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.