Publishing to Azure - ApplicationDbContext in Settings is Empty - asp.net-mvc

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; }
}

Related

How do i create a class library proejct to handle my migrations and database objects in entity framework core 2.2?

I have created a .net core 2.2 web mvc application. I then created a .net core 2.2 class library to contain all my database models. When attempting to run the initial migration i get the error cannot create object of type 'X'.
I have referenced my class library in the main web project, set it as the startup and in the package manager console i set the default project as the class library.
I expected this to create my migrations but i get this error.
public class ProjectWalesDbContext : DbContext
{
public ProjectWalesDbContext(DbContextOptions<ProjectWalesDbContext> options)
: base(options)
{ }
public DbSet<User> Users { get; set; }
public DbSet<UserCourse> UserCourses { get; set; }
public DbSet<Course> UserCourse { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Property(b => b.created_at)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<User>()
.Property(b => b.password_reset_date)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<User>()
.Property(b => b.password_reset_required)
.HasDefaultValueSql("0");
modelBuilder.Entity<UserCourse>()
.Property(b => b.course_progress)
.HasDefaultValueSql("0");
}
}
this is my db context that i set up ive set it up the same way in other projects so i cant see what ive done wrong if anything. any help would be greatly appreciated
Solved, I needed to add the line:
services.AddDbContext<ProjectWalesDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
to the start-up of the web app so I could create the context.

add-migration 'InitialModel' is showing database access error

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.

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.

Trying to move asp.net identity tables to my database

hello I'm trying to make an online store mvc applciation with view model and onion architecture. So in My interfaces folder I have my db context
class OnlineStoreDBContext:DbContext
{
public DbSet<Language> Languages { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<CategoryLanguages> CategoryLanguages{ get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<ProductLanguages> ProductLanguages { get; set; }
public DbSet<ProductCategories> ProuctCategories { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetails> OrderDetails { get; set; }
public DbSet<Customer> Customers { get; set; }
}
And in my web.config of my mvc applciation I have the following connection to my database
<add name="OnlineStoreDBContext" connectionString="Data Source=.\SQLexpress;Initial Catalog=OnlineStore;Integrated Security= true" providerName="System.Data.SqlClient" />
1.Now I try to use asp.net identity in visual studio 2013 BUT I WANT THE TABLES WHICH
IDENTITY CREATES TO BE IN MY DATABASE OnlineStore which tables I create using the Code first Entity framework approach .
As I want to extend user class can you provide me with a simple way to add more more field for the user identity.
I appreciate any help
I am very unfamiliar with MVC thing, sadly I can say.. But what I do in a similar situation was to create a connection string to your own DB in the web.config file but name it "DefaultConnection"
<add name="DefaultConnection" connectionString="Data Source=.\SQLexpress;Initial Catalog=OnlineStore;Integrated Security= true" providerName="System.Data.SqlClient" />
Then I run the application and proceeded to Register and registered as a user... Then I saw that the schema was created in my DB. Then I supposed you can add your own tables and stuff in that DB..
"1. As I want to extend user class can you provide me with a simple way to add more more field for the user identity."
If I haven't gotten it wrong you meant to add additional profile information. I am new a ASP.net Identity but with a quick search I found:
http://www.itorian.com/2013/11/customize-users-profile-in-aspnet.html
http://www.c-sharpcorner.com/UploadFile/4b0136/adding-profile-data-in-Asp-Net-identity-using-visual-studio/
Hope I helped a bit..

Resources