Why is the Seed method called again in my EF code first migrations scenario? - ef-code-first

I have a EF code first project and there is how I seed the database
internal sealed class Configuration : DbMigrationsConfiguration<myDB>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "myDB.Auth.Service.DAL.myDB";
}
protected override void Seed(myDBdb)
{
var mProduct = new Product
{
Name = "default product",
CreatedDate = DateTime.Now
};
db.Products.AddOrUpdate(mProduct);
db.SaveChanges();
}
}
I have a wcf service that uses above code. What I realise is that every time I restart the wcf service (either from visual studio or IIS), above code is get called. As a result, multiple "default product" are added into the database, anyone knows why that happened?

Migration seed runs after every update-database so you need to make your script idempotent by testing for existance or using AddOrUpdate. If you only want to seed on database creation, there is a separate context seed method that only runs when the database is created.
https://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/
AddOrUpdate for seeding
Edit:
When you use MigrateDatabaseToLatestVersion initializer, your seed method runs every time your application runs. If you want to control this process, switch your initializer to null:
Database.SetInitializer(new NullDatabaseInitializer<ApplicationDbContext>());
And then just manually run migrations when needed. To take it a step further, you can write your own initializer and do what you want when either the database does not exist or the database needs updating:
Database.SetInitializer(new ValidateDbInitializer<ApplicationDbContext>());
// ref: https://coding.abel.nu/2012/03/prevent-ef-migrations-from-creating-or-changing-the-database/
public class ValidateDbInitializer<TContext> : IDatabaseInitializer<TContext>
where TContext : ApplicationDbContext
{
public void InitializeDatabase(TContext context)
{
if (!context.Database.Exists())
{
throw new InvalidOperationException("The database does not exist. Check your server and connection string.");
}
if (!context.Database.CompatibleWithModel(true))
{
throw new InvalidOperationException("The database is not up to date. You may need to apply update(s).");
}
}
}

First step is to use the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window type the below command.
Enable-Migrations
which will adds folder named as Migrations in your project and also a code file called as Configuration.cs.
in Configuration.cs type the below line
using yourprojectname.Models;
protected override void Seed(yourprojectname.Models.MyServiceContext context)
{
context.MyDB.AddOrUpdate(x => x.Id,
new MyData() { Name = "Mohit", CreatedDate= "14/05/2016" },
new MyData() { Name = "Prabhat", CreatedDate= "15/05/2016" },
);
}
Now type Update-Database
in Package Manager Console window

Try the following:
protected override void Seed(myDBdb)
{
var mProduct = new Product
{
Id = 1,
Name = "default product",
CreatedDate = DateTime.Now
};
db.Products.AddOrUpdate(mProduct);
db.SaveChanges();
}

When you are using the application for initialization the Data for the first time, please use DropCreateDatabaseAlways. e.g. :
public class MyClass : DropCreateDatabaseAlways<connectionstringContextName>
{
protected override void Seed(MyContext context)
{
// Your seed data
}
}

Related

Xamarin.Forms and EntityFrameworkCore 3.x how to properly create a database and apply migrations?

what is the proper way to create an EF Core database on an Android/iOS device with Xamarin.Forms and EntityFrameworkCore?
I've come across the EnsureCreated vs Migrate thing and since I'm planning on changing the database structure in the future, I'd like to be able to apply those migrations to an existing database, thus I've chosen the Migrate approach.
However, when I call the Migrate method, it doesn't seem to create a database. I've managed to make it work in case I copy the pre-generated database file on the devices beforehand, but that's not what I want. Is there a way to tell EF Core to check if there's an existing database, create a new database if not, and then apply pending migrations to it?
Here's what I've done so far:
I've created a .net standard class library "Data" that will hold all my database classes (context, models, and migrations).
I've changed the TargetFramework of the "Data" project from <TargetFramework>netstandard2.0</TargetFramework> to <TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks> so I could run PMC commands on it.
I've installed these nuget packages to the "Data" project:
EntityFrameworkCore
EntityFrameworkCore.Sqlite
EntityFrameworkCore.Tools
EntityFrameworkCore.Design
I've created a database context class. I've made two constructors for it. The default one will only be used by the PMC commands for generating migrations. The other one will be used in production.
public class MyTestContext : DbContext
{
private string _databasePath;
public DbSet<Issue> Issues { get; set; }
[Obsolete("Don't use this for production. This is only for creating migrations.")]
public MyTestContext() : this("nothing.db")
{
}
public MyTestContext(string databasePath)
{
_databasePath = databasePath;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//I've also tried Filename={_databasePath} here, didn't work either
optionsBuilder.UseSqlite($"Data Source={_databasePath}");
}
}
I've created a test model class, just to have something to play with
public class Issue
{
public string Id { get; set; }
}
I created an inital migration using this command, which completed successfully:
Add-Migration Migration001 -Context MyTestContext -Output Migrations
I added a call to the Migrate method in the App.xaml.cs of my Xamarin.Forms project to test if it works.
public partial class App : Application{
//... other code
protected override async void OnStart()
{
base.OnStart();
using (var db = new MyTestContext(_dbPath))
{
try
{
db.Database.Migrate();
db.Issues.Add(new Issue
{
Id = "TestIssueId"
});
db.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
//... other code
}
The _dbPath variable contains this (on Android where I'm testing it):
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "test.db");
After all this, I'm getting this exception:
Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: Issues'.

Issues deploying mvc application that has users and needs an update on the database

I am trying to seed an admin user to my database so that when I deploy, I have one user that can log in....
This is the seed method that I am trying to run, but it gives me "no suitable method found to override". My application user is the stock application user that visual studio gives you in the template.
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
var passwordHash = new PasswordHasher();
string password = passwordHash.HashPassword("Password#123");
context.Users.AddOrUpdate(u => u.UserName,
new ApplicationUser
{
UserName = "Steve#Steve.com",
PasswordHash = password,
PhoneNumber = "08869879"
});
}
Class where you override Seed method need inheriting from DropCreateDatabaseAlways<TContext>.
Error :
no suitable method found to override
Mean only that base class not contains Seed method. You can override it like:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
protected override void Seed(YourContext context)
{
//add data
}
}

EntityException occurred in EntityFramework.SqlServer.dll

My Controller code
ParaEntities db = new ParaEntities();
public List<Client> GetAllClients()
{
return db.Client.ToList();
}
Please click this link to see the error message
It is weird that when I am first time to click the button to get all client information then it responses 500. In the second time, I click the button to get all client, which is success.
You should assign variable and display the data in View.
Please change the syntax as i write below.
ParaEntities db = new ParaEntities();
public List<Client> GetAllClients()
{
var getData= db.Client.ToList();
if(getData==null)
{
return null;
}
return getData;
}
This error points to a connection problem rather then code issue. Check that the connectionstring is valid and that the user specified in the connectionstring has access to the database. If you're running the application on IIS then make sure that the applicationpool user has access to the database. Here is another SO issue were they solved this error.
If you want to store the db context as a local variable in your controller class then I suggest you to instantiate it inside of the controllers constructor. Then you make sure that every time a instance of the controller is created then a new db context is created as well.
Lets say your controller namned ClientController
private ParaEntities db;
public ClientController()
{
this.db = new ParaEntities();
}
public List<Client> GetAllClients()
{
return db.Client.ToList();
}
Another approach is to wrap your db context in a using statment inside of your method. In that case you make sure that the method is using a fresh context when being called upon and that the context is being disposed when the operation is completed.
public List<Client> GetAllClients()
{
using(ParaEntities db = new ParaEntities())
{
return db.Client.ToList();
}
}
PS: both examples violates the dependency inversion principle (hard coupling to the db context) but thats for another day
Please try this
public List<Client> GetAllClients()
{
ParaEntities db = new ParaEntities();
return db.Client.ToList();
}

Code First Mapping to Database Views

I have been asked to map the ASP.NET Identity classes to existing database Views for read operations, using Stored Procedures for CRUD. There are a number of StackOverflow Questions stating that is possible to map to views, also this question, this one and lastly this one.
I have mapped the classes to the Views as follows-
var applicationUser = modelBuilder.Entity<applicationUser>().HasKey(au => au.Id) //Specify our own View and Stored Procedure names instead of the default tables
.ToTable("User", "Users").MapToStoredProcedures(sp =>
{
sp.Delete(d => d.HasName("spUser_Delete", "Users"));
sp.Insert(i => i.HasName("spUser_Create", "Users"));
sp.Delete(u => u.HasName("spUser_Update", "Users"));
});
Where [Users].[User] is a SQL view retrieving data from the SQL table [Users].[tblUser].
Unfortunately I have had to leave at least one of the classes mapped to a table rather than View as Entity Framework generates the following SQL-
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND (t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('Users.ApplicationRole','Users.User','Users.AuthenticationToken','Users.UserClaim','Users.UserLogin','Users.UserRole','Users.Department','Users.PasswordResetToken','Users.UserDepartment')
OR t.TABLE_NAME = 'EdmMetadata')
go
Which returns zero as these are Views and not tables.
As a result any attempt to use the UserManager results in the exception-
Value cannot be null. Parameter name: source
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source
Source Error:
Line 48: if (ModelState.IsValid)
Line 49: {
Line 50: var userAccount = await
UserManager.FindByNameAsync(model.UserName);
Line 51:
Line 52: if (userAccount == null)
Manually changing the query to-
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE (t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('Users.ApplicationRole','Users.User','Users.AuthenticationToken','Users.UserClaim','Users.UserLogin','Users.UserRole','Users.Department','Users.PasswordResetToken','Users.UserDepartment')
OR t.TABLE_NAME = 'EdmMetadata')
go
Returns the correct nine Views and would presumably not cause the error. Simply having one of the classes mapped to a table is sufficient to convince it the database is correct and to carry on as normal.
Is there any way I can persuade Entity Framework to remove the "Is a table" requirement, or assert that the tables do exist and therefore skip this step altogether?
Edit: Following a request, the code for the UserManager is included below-
AccountController.cs
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationIdentityDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
I have managed to resolve this problem by creating a custom Database Initializer which replaces the default CreateDatabaseIfNotExists initializer. The Codeguru article on Understanding Database Initializers in Entity Framework Code First was enormously helpful in helping me understand what was going on.
Code for solution-
using System.Data.Entity;
namespace NexGen.Data.Identity
{
public class IdentityCustomInitializer : IDatabaseInitializer<ApplicationIdentityDbContext>
{
public void InitializeDatabase(ApplicationIdentityDbContext)
{
return; //Do nothing, database will already have been created using scripts
}
}
}
IdentityManager-
public class ApplicationIdentityDbContext: IdentityDbContext<ApplicationUser>
{
public ApplicationIdentityDbContext() : base("DefaultConnection")
{
Database.SetInitializer(new IdentityCustomInitializer());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
As a result of this code there are no longer any probing queries by Entity Framework attempting to check if the database exists (and failing due to the assumption that tables, rather than views, were mapped) - instead the queries are immediately against the view attempting to retrieve the user data (and then executing a Stored Procedure in the case the initial action was a registration or otherwise updating the user).
please try
[Authorize]
public class AccountController : Controller
{
public AccountController()
{
InitAccountController(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationIdentityDbContext())))
}
private InitAccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
}
some more explanations:
in EF6 code we can see the following function (DatabaseTableChecker.cs):
public bool AnyModelTableExistsInDatabase(
ObjectContext context, DbConnection connection, List<EntitySet> modelTables, string edmMetadataContextTableName)
{
var modelTablesListBuilder = new StringBuilder();
foreach (var modelTable in modelTables)
{
modelTablesListBuilder.Append("'");
modelTablesListBuilder.Append((string)modelTable.MetadataProperties["Schema"].Value);
modelTablesListBuilder.Append(".");
modelTablesListBuilder.Append(GetTableName(modelTable));
modelTablesListBuilder.Append("',");
}
modelTablesListBuilder.Remove(modelTablesListBuilder.Length - 1, 1);
using (var command = new InterceptableDbCommand(
connection.CreateCommand(), context.InterceptionContext))
{
command.CommandText = #"
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE t.TABLE_TYPE = 'BASE TABLE'
AND (t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN (" + modelTablesListBuilder + #")
OR t.TABLE_NAME = '" + edmMetadataContextTableName + "')";
var executionStrategy = DbProviderServices.GetExecutionStrategy(connection);
try
{
return executionStrategy.Execute(
() =>
{
if (connection.State == ConnectionState.Broken)
{
connection.Close();
}
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
return (int)command.ExecuteScalar() > 0;
});
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
which corresponds to what you discover.
From this function we may says that there is a problem if, and only if, there are/is only views mapped to the model. In this case the initializer considers the database as Existing but Empty, and he tries to create the tables.
This creates problems as there are/is still views in the database with the same name as the tables the initializer wants to create.
So a work around seems to have at least one real table mapped to the context. No need for a custom initializer in this case.
I propose it as an issue : model only mapped to views
From my understanding and tests there is no need to implement an IDatabaseInitializer having an empty InitializeDatabase method like pwdst did.
From what I saw at Understanding Database Initializers in Entity Framework Code First, it is sufficient to call
Database.SetInitializer<ApplicationIdentityDbContext>(null);
when the application is initializing, or better say, before the first time the database will be accessed.
I would not put it inside the ctor of my DbContext class to avoid setting the initializer every time a DbContext instance is created. Instead, I would put it into the application's initialization method or as one of the first statements of the Main() method.
This worked fine for my application using Entity Framework 6.

Confusion about generation of database and seeding

I am using entity framework code first
and also I have data seeding code
Now when I run my application my database gets generated but is not seeded with my dummy data.
I have to run entity framework once more to get all data populated.
Any idea why and how to fix that so i do not have to run my app 2x to get database and data?
thnx
my context definition file is:
public class Context : DbContext
{
public DbSet<Task> Tasks { get; set; }
public DbSet<Agency> Agency { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
And here is my seeding file
public class Configuration : DbMigrationsConfiguration<Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(Context context)
{
GenerateTasks(context);
context.SaveChanges();
}
private static void GenerateTasks(Context context)
{
if (context.Task.Any()) return;
context.Task.Add(new Task() { Name = "Received" });
}
}
And hook to create database is:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
var context = new Context();
context.Database.Initialize(true);
If your app is an ASP.NET one and is a seperate assembly from the data layer, then you can, instead of configuring the initialization like you did, configure it directly in the web.config. Maybe this is the reason for your problem.
So if it's an ASP.NET app, you can try the following:
(1)
Comment this out:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
var context = new Context();
context.Database.Initialize(true);
(2)
In web.config, insert this right at the end before the closing /configuration tag:
<entityFramework>
<contexts>
<context type="**fully-qualified name of your context class**,
**assembly name of your context**">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[**fully-qualified name of your context class**, **assembly name of your context**],
[**fully-qualified configuration type**, **assembly name of your context**, Version=1.0.0.0, Culture=neutral]], EntityFramework"/>
</context>
</contexts>
where fully-qualified configuration type is the class with your migrations-configuration (something like [...]Context.Migrations.Configuration)
I use this configuration-approach for myself in my projects and it works well!
That's true. call context.Tasks.Find(1) and then it will hit the database.
EF code-first uses this trick to postpone every thing. this way application's startup time seems much faster. (but actually it's not!)

Resources