Search code examples
entity-frameworkinsertdbcontextseedingno-data

Entity Framework not inserting data at all


First time I am facing this, when using the base.Seed(context) or using the context.SaveChanges() EF will not insert any data into the database.

This is my setup:

Context

public ApplicationDbContext() : base("DbName")
{         
    Database.SetInitializer(new NameOfSeeder()); 
}

Seeder

public class NameOfSeeder : DropCreateDatabaseAlways<ApplicationDbContext> 
{
    protected override void Seed(ApplicationDbContext ctx)
    {           
        Language newLanguage = new Language("Nederlands");
        ctx.Languages.AddOrUpdate(l => l.Name, newLanguage);

        // using this won't work either
        ctx.Languages.Add(newLanguage);

        base.Seed(ctx); // => this should work, never had any issue with this untill now ...
        //ctx.SaveChanges(); // this does not work either
    }
}

I also tried adding this to my first action (Index => HomeController)

using (ApplicationDbContext ctx = new ApplicationDbContext())
{
    //if (ctx.Languages.Any()) { }

    Language newLanguage = new Language("Nederlands");
    ctx.Languages.Add(newLanguage);
    ctx.SaveChanges();
}

The Web.config

<add name="DbName" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DbName.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

This is really the first time ever that I am having this, NO IDEA what is causing this ... Any help please is really appreciated!

EDIT:

  • I am using Azure AD authentication

  • EF Migrations as well (added Migrations today but that didn't changed anything)

  • using Database.SetInitializer(new DropCreateDatabaseAlways()); didn't work either


Solution

  • OK so i didn't expect EF NOT to throw an exception in such cases but i did wrap the Seed() method in a Try Catch and guess what:

    Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    

    So yeah i solved the Validation errors and everything is working as it should. Kind regards.