add-migration 'InitialModel' is showing database access error - asp.net-mvc

After enabling the migrations, I tried to add the first migration using add-migration 'InitialModel'. I am attaching the The MyDBContext.cs file code.
{
public class MyDBContext : DbContext
{
public DbSet<Customer> Customers { get; set; } // My domain models
public DbSet<Movie> Movies { get; set; } // My domain models
}
}
An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.

Related

Publishing to Azure - ApplicationDbContext in Settings is Empty

I'm a little stuck here, and can't seem to get my database working on Azure after deploying, however everything works fine on my local machine.
What I've done so far is:
1) Logged into Azure
2) Created a website
3) Created a Database
4) Downloaded the 'Publish Profile' file
5) Enabled migrations on my App
7) Removed my DbContext class - NEVERMIND, I kept it. I removed the store initializer.
6) App > Publish > Import > (imported the publish profile)
However, when I go to Settings and check ApplicationDbContext, its blank. Furthermore, when I visit the site after it pushes to the cloud, I get the:
[Win32Exception (0x80004005): The system cannot find the file specified]
...which is expected because the db isn't connected properly.
Any ideas would be greatly appreciated.
EDIT:
ApplicationDbContext Class is as follows:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DataContext") { }
public DbSet<Program> Programs { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Suggestion> Suggestions { get; set; }
public DbSet<FollowUp> FollowUps { get; set; }
public System.Data.Entity.DbSet<Suggestions.Controllers.SuggestionBase> SuggestionBases { get; set; }
}

Entity Framework migration history not recognized after Identity 2.0 upgrade?

I am in the process of upgrading from Simple Membership to Identity 2.0 in my existing web project. Some of the bigger changes that involve entity framework is the DBContext inheritance and UserProfiles changing to Users.
I use PMC to add migrations and update the database instead of allowing automatic migrations at run time.
The expectation is that after my code changes for getting to Identity 2.0 that I would add a migration and it would generate the schema changes into my migrations folder.
For some reason it is no longer recognizing the existing migration history table in the current db! When I run add-migration it says there are existing migrations that aren't applied and that I should run update-database first. I run update-database -script to see what it was trying to do and it wants to create the migration history table and each migration in my project.
It seems that somehow the migration history table is no longer recognized. I ran get-migrations to confirm it was talking to the correct database and it was but no migrations have been applied.
Running Entity Framework 6.1.1
Any suggestions?
internal sealed class Configuration : DbMigrationsConfiguration<Namespace.MyContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(Namespace.MyContext context)
{
//Stuff to initialize an empty db
}
public class UserProfile : IdentityUser<int, CustomIdentityUserLogin, CustomIdentityUserRole, CustomIdentityUserClaim>, IUser<int>
{
[Required]
public string Name { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserProfile, int> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//other properties related to the user profile
}
Edit 2:
As a test, I deleted the migrationhistory table, ran "update-database -targetmigration mostcurrentmigraiton -script", then deleted out all the changes except for the migration history from the script, ran the script.
I then tried to get-migrations and still "no migrations have been applied to the target database" appeared. I verified that it did create the table and the product version had updated for previous migrations where they were older.
Please help!
I wanted to add comment but it has gone too long.
First option: try update-database -force in PCM.
Second option: if this is not already deployed web application and you don't care about data loss yet, my answer here can help: Second attempt to generate script sql script did not work
Third option: There is one thing more that comes to my mind. If you create new ASP .NET MVC 5.1 with template including Identity 2.0 you get class IdentityModels.cs in Models. It looks like this:
namespace WebApplication2.Models {
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser {
PROPERTIES OF APPLICATION USER HERE
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false) {
System.Diagnostics.Debug.WriteLine("CONSTRUCTOR");
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
//stuff in database
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
}
public static ApplicationDbContext Create() {
return new ApplicationDbContext();
}
}
}
and then in Application_Start() in Global.asax you have:
protected void Application_Start() {
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
new ApplicationDbContext().Database.Initialize(true);
...more stuff
}
and your code might lack these two lines from Application_Start but with your DbContext(I used ApplicationDbContext here).
If this didn't help, sorry, I am out of options.
After much troubleshooting I found the problem to be one that must be security related. Get-Migrations will return the message I have seen when no password is entered in the connection string that the dbcontext is using. Interestingly enough, using localdb for development, I had the correct username and password as the update-database was able to create new tables but some level of access must not be available for it to get the migrations. What I found most strange is that get-migrations didn't say there was a credential issue!

Publishing with Multiple Context in Same Database

I encountered a problem with multiple context in EF 6. Recently i had splitted my context into three parts and configured them as had been told here
Everything was fine, until i decided to publish via Visual Studio; because publish wizard detected only one of my context instead of three. And interestingly everytime it detects same context, i couldn't find why, neither first letter of name nor any difference from the others seem cause this.
But i couldn't publish my MVC project because of this. I have to migrate all three contexts while publishing.
After some search, i saw Update-Database command gets connectionstring parameter. This is my last option, if there isn't any way to solve publish wizard i try to update database with this code.
I haven't been able to reproduce this issue. Here are the steps I used (using Visual Studio 2013 Update 2).
Create a new MVC application. Add the following models to the project (two separate Code First models/contexts).
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
}
public class ProductContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Then enable migrations, add a migration and update the local database for both contexts, using the following commands.
Enable-Migrations -ContextTypeName CustomerContext -MigrationsDirectory Migrations\Customer
Enable-Migrations -ContextTypeName ProductContext -MigrationsDirectory Migrations\Product
Add-Migration FirstMigration -ConfigurationTypeName MyWebApp.Migrations.Customer.Configuration
Add-Migration FirstMigration -ConfigurationTypeName MyWebApp.Migrations.Product.Configuration
Update-Database -ConfigurationTypeName MyWebApp.Migrations.Customer.Configuration
Update-Database -ConfigurationTypeName MyWebApp.Migrations.Product.Configuration
Then when I right-click -> Publish the project I get the option to enable migrations on App_Start for both of my contexts (and the ASP.NET Identity context too). If I understand correctly, you are not seeing your additional context(s) in this screen.
I've seen this happen when multiple DbContexts share a common connection string. By this I mean:
public class Context1: DbContext
{
public Context1()
: this("DefaultConnection")
{}
public Context1: (string connectionString)
: base(connectionString)
{}
....
}
public class Context2: DbContext
{
public Context2()
: this("DefaultConnection")
{}
public Context2: (string connectionString)
: base(connectionString)
{}
...
}
When you Publish, only one DbContext will show up under Settings > Databases. If you change "DefaultConnection" to something else then you will see the distinct DbContexts. Like this:
public class Context1: DbContext
{
public Context1()
: this("DefaultConnection")
{}
public Context1: (string connectionString)
: base(connectionString)
{}
....
}
public class Context2: DbContext
{
public Context2()
: this("DefaultConnection2")
{}
public Context2: (string connectionString)
: base(connectionString)
{}
...
}
Maybe this explains the behavior you are seeing.
If both dbContexts are using the same database (and therefore the same database connection string in web.config), how do we get Web Deploy to show them both? Do I have to create a separate (duplicate) connection string that points to the same database just to get it to show up as a separate context in the wizard?
When you want to see all contexts in the Publish dialog, you need to add another connection strings to web.config. They should have different name and be referenced from your context (name in constructor)

Entity Framework -Update-Database- Does not create Database

Visual Studio 2013
I am trying to learn asp.net MVC over at PluralSight. I created a project(dll) called eManagr.Domain with the following classes:
Department / Employee / IDepartmentDatasource
Department.cs
public class Department
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Employee.cs
public class Employee
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
IDepartmentDataSource
public interface IDepartmentDataSource
{
IQueryable<Employee> Employees { get; }
IQueryable<Department> Departments { get; }
}
I created an infrastructure folder with the following file : DepartmentDb.cs
public class DepartmentDb : DbContext, IDepartmentDataSource
{
public DbSet<Employee> Employees {get; set;}
public DbSet<Department> Departments {get; set;}
IQueryable<Employee> IDepartmentDataSource.Employees
{
get { return Employees; }
}
IQueryable<Department> IDepartmentDataSource.Departments
{
get { return Departments; }
}
}
I then created another project using MVC 4 called eManager.Web with Internet Template during the creation of the project.
When running Enable-Migration it says I have two[eWeb.Domain , eWeb.Model.Users] which then I tell it Enable-Migration with the following command:
Enable-Migration -ContextTypeName DepartmentDb
which creates the migration folder and a file called Configurations.cs
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(eManager.Web.Infrastructure.DepartmentDb context)
{
context.Departments.AddOrUpdate(t => t.Name,
new Department() { Name="Engineering"},
new Department() { Name = "Sales" },
new Department() { Name = "Shipping" },
new Department() { Name = "HR" }
);
}
EDIT -- Connection String from Web.Config --
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-eManager.Web-20140216202751;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-eManager.Web-20140216202751.mdf" providerName="System.Data.SqlClient" />
When I run the following I get the following reponse:
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Running Seed method.
PM>
After this runs, I suppose to see a database file in my App_Data but it does not exist and when I use SQL Server Object Explorer, the database is not created even though that is what I am trying to do.
Could you provide your connection string from Web.config?
Also, is there a Data Connection (Server Explorer -> Data Connections) named the same as your connection String?
I think, adding a parameter-less constructor to your DepartmentDb context class could solve your problem
public DepartmentDb ()
: base("name=DefaultConnection")
Where name=DefaultConnection has to be your connection string name
I noticed that you enabled your migration in the correct way, have you run:
add-migration "give it a name" ?
once this has been completed you will notice a new file in the migrations folder.
you wont be able to update database with out creating a new migration.
I just ran into something very similar. I encountered it when I was going through the following ASP.NET MVC tutorial:
https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
In my case, the problem seemed to be that I already had a database table of that name. I had gone through the tutorial partway previously about a month ago, but was interrupted and had to abort. Even though I deleted the entire Project, it seemed that the database table name may have been retained.
I say seemed to be, because the problem disappeared with the following solution: after a 2nd delete of the project, I carefully substituted 'Contoso' for 'ContosoUniversity' in every relevant situation.
Before the problem was solved, I was repeatedly getting the (0x80131904-error) in the Package Manager Console when trying to update-database, and a notice that the mdf file could not be connected to the database. However, when I checked the appropriate directory, the mdf file was not even being created.
FYI For beginning MVC-ers in Visual Studio 2012, I do recommend going through the following MVC tutorial before the one above.
https://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
A MVC5 Visual Studio 2013 version is also available through that link.
The tutorial of the first paragraph makes a few jumps...
I could not have debugged the issue if I'd started with the EF5 tutorial as my first MVC project.

DbContext Errors in Azure Worker Role when using Unity

I have an Azure worker role with a UnitOfWork class that looks something like this:
public class UnitOfWork : IUnitOfWork
{
public MyData Db { get; private set; }
public ILoginRepository LoginRepository { get; private set; }
public ISubscriptionRepository SubscriptionRepository { get; private set; }
public UnitOfWork(MyData db,
ILoginRepository loginRepository,
ISubscriptionRepository subscriptionRepository)
{
}
}
The repositories accept a reference to the DbContext as well:
public class LoginRepository : Repository<Login>, ILoginRepository
{
public LoginRepository(MyData db) : base(db) { }
}
I would think this is pretty straight-forward.
Now, I'd like to configure my code-first DbContext in Unity so that each time a UnitOfWork is resolved a new DbContext is created and all subsequently resolved repositories get it too.
I'd think that PerResolveLifetimeManager would do the trick:
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<MyData, MyData>(new PerResolveLifetimeManager());
But it does not. I get all these weird SQL-related errors, such as:
"New transaction is not allowed because there are other threads running in the session."
What gives?
You are talking about PerResolveLifetimeManager but you are using PerThreadLifetimeManager (which is said to be buggy anyways) in your code. May that be the cause of your problems?
Ok, I refactored the solution to do much more explicit Resolve calls instead of .ctor injection and then after all that I realized the main issue was around trying to update an object while iterating over an IQueryable that contained it.
Much ado about nothing, seems to me.
Thanks for the help.

Resources