I created a new ASP.NET MVC project, I am using code-first. I have added ASP.NET Identity to this project enabled-migrations and can see the tables in my database on sql server express.
I have a "DefaultConnection" which points to my database on sqlserver like so:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;database=worksmartDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Now, I am confused how to add my entities to the same database via code first? Below is my structure:
Models
Applicant
Template
MyProjectContext(which dervies from DBContext)
public class MyProjectContext: DbContext
{
public MyProjectContext() : base("DefaultConnection")
{
}
public DbSet<Applicant> Applicants { get; set; }
public DbSet<Template> Templates { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
I try to enable migrations for this context but I receive the following error:
The context type 'MyProjectContext' was not found in the assembly 'MyProject'
I want to use same database for identity and entities.
Well I got it to work, not sure if this is the correct method.
However,
When you add identity into a new project, you should do the following:
- Change public ApplicationDbContext()
: base("YourConnection", throwIfV1Schema: false)
Note: this connection string should point to the same database you are going to use
- Run the application in browser
- Register a user (this will create the database for you, if one does not exist)
- Now Enable-Migrations
- Update-Database
And this is one way of adding identity into your project.
Related
need help i am new to MVC and EF
So i am trying to create a DB using the code first Approach.
I have specifed the following Connection String
<add connectionString="Data Source=(local);Initial Catalog=SalesERPDB;Integrated Security=True"
name="SalesERPDAL"
providerName="System.Data.SqlClient"/>
</connectionStrings>
and i was in a hope that EF will create a DB with the name SalesERPDB. Instead it has created a DB with the following name"MVC.DataAccessLayer.SalesERPDAL". where MVC.DataAccessLayer is the namespace where SalesERPDAL (a class) is declared which is inheriting DBcontext.
in short EF is naming the database with the fully qualified name of the class which is inhering DBcontext.
namespace MVC.DataAccessLayer
{
public class SalesERPDAL : DbContext //i think it will help in interacting with DB
{
protected override void OnModelCreating(DbModelBuilder modelBuilder) //i think used to build a model
{
modelBuilder.Entity<Employee>().ToTable("TblEmployee");
base.OnModelCreating(modelBuilder);
}
public DbSet<Employee> DALEmployees { get; set; } //Dbset will represent all the employees that can be queried from the database.
}
}
i have 2 questions:
Why is it taking the particular name instead of connection string's name?
How can i modify my code such that i get access to name my server as i want?
Sorry if it is repeated question.
Your constructor method is missing. ConnectionString name should be given as a parameter to base method, so that your application can know with what name to create a database. Otherwise it creates the database named as your DbContext class name (which is MVC.DataAccessLayer.SalesERPDAL).
A constructor method can be added such as:
public SalesERPDAL() : base("SalesERPDAL") { }
So I build my asp.net web project using MVC and it's working fine in localhost using code-first approach of EntityFramework 6.0.
This week I bought a new Web Hosting to upload my website.
The problem is that, everytime I run the website it tries to create a database in database 'master', why is this happening?
I am selecting the right database that my Web Hosting provided on my ConnectionString.
There is a note: I am also using ASP Identity OWIN... maybe that's the problem? it's using another ConnectionString ?
My Identity Config (Used for OWIN):
namespace MyNamespace
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new MyContext());
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Login"),
});
FormsAuthentication.SetAuthCookie("CookieValue", false);
}
}
}
And here is my DbContext called MyContext:
namespace MyNamespace.DAL
{
public class MyContext : IdentityDbContext<IdentityUser>
{
public MyContext() : base("MyNamespace.DAL.MyContext")
{
if (!Roles.Any(r => r.Name == "admin"))
{
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this));
RoleManager.Create(new IdentityRole("admin"));
}
if (!Users.Any(u => u.UserName == "myuser"))
{
var store = new UserStore<IdentityUser>(this);
var manager = new UserManager<IdentityUser>(store);
var user = new IdentityUser { UserName = "myuser" };
manager.Create(user, "mypw123");
manager.AddToRole(user.Id, "admin");
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Item1> stuff1 { get; set; }
public DbSet<Item2> stuff2 { get; set; }
public DbSet<Item3> stuff3 { get; set; }
public DbSet<Item4> stuff4 { get; set; }
public DbSet<Item5> stuff5 { get; set; }
}
}
Here is my Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections></configSections>
<appSettings>
<add key="owin:AppStartup" value="MyNamespace.IdentityConfig" />
</appSettings>
<connectionStrings>
<add name="MyNamespace.DAL.MyContext" providerName="System.Data.SqlClient" connectionString="server=myhostingmssql07; uid=myuserid_en_wmx00; database=mydbname_en_wmx00; password=mybdpw;" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="Off"/>
<trust level="Full" />
</system.web>
<!--More stuff here..-->
</configuration>
PS: I know that this mechanism I used to create default admins is not the best approach, I will change it to a seed method later, I just need to put this working right now, then I will handle all the refactoring.
PS2: The log message causing the error (I am using customErrors = Off as you can see above) is on the following line:
if (!Roles.Any(r => r.Name == "admin"))
This line triggers a create database on database 'master' , that's not what is specified on ConnectionString!!
It should create all the DbContext and IdentityDbContext tables on the Database called "mydbname_en_wmx00" as you can see above in ConnectionString..
I tried using EntityFramework Default Factory on Web.Config using as parameter value the same ConnectionString and I started getting (Internal Server Error 500), so I just rolled back and deleted this EntityFramework Default Factory configuration...
PS3: I know that if I use the following Initializer on MyContext constructor:
Database.SetInitializer<MyContext>(null);
it doesn't trigger any CREATE on Database and everything goes okay, the problem is that I need to set up everything manually on Database, like AspNetRoles and AspNetUsers, etc etc, and all my DbContext Tables (Stuff1, stuff2, etc).
PS4: Maybe you are thinking this link is a duplicate question, but it's not, he is using local SQLEXPRESS instance, and I am using a remote mssql from my paid host...
Thank you so much for your effort, do you know by any chance, what is happening here? EF Code-First auto-generate databases don't work on Paid-Web-Hostings??
It seems it's a problem from my paid web-hosting..
There isn't support for code-first approaches (that includes running Update Migrations and Seed Methods from Package Manager Console), because it always reference the 'master' Database which I don't have permissions, as you might know..
So I figured it out a workaround, I generate a full SQL Script from my Context and Models and then I just run the SQL Script on my Remote Database Server using a tool from their system, and all the tables are created according to each model specification.
To generate the SQL Script I run the following command on the Package Manager Console (make sure you typed Enable-Migrations before - if you can't Enable-Migrations because your remote host on the ConnectionString doesn't allow it, just create a new ConnectionString pointing to your local db and then run again "Enable-Migrations -Force" it will work, it did for me):
Update-Database -Script -SourceMigration:0
Then don't forget to tell your EF Contexts that you are using a null DatabaseInitializer so it doesn't try to drop/create a new Database using code-first approach:
Database.SetInitializer<YourContext>(null);
Thanks to StackOverFlow I found this solution, how lucky we are nowadays!
Hello every one
I am new in .net MVC3 I have made a connection string in Web.config file, the connection is successfully created. below is my connection code
<add name="StoreDB" connectionString="Data Source=AMIT-PC;Initial Catalog=Store;User ID=sa;Password=****;Integrated Security=False"
providerName="System.Data.SqlClient" />
After that i created DBConfig.cs class file for database table connection below is my code
public class Store : DbContext
{
public Store()
{
}
public DbSet<RegisterModel> myapp { get; set; }
public DbSet<Application> ApplicationFormModels { get; set; }
}
There are basically two model i have created. First is RegisterModel and Seconds is Application model.
When I run this code the error occured
The model backing the context has changed since the database was created.
When I use only one DbSet<RegisterModel> than the table is successfully created and all the CURD operation are successfully done but error occured when i create more than one DbSet.
Below is the screenshots
looking forward for your inputs
Thanks in Advance
Go to your
Global.asax-->Application_Start() and add Database.SetInitializer<YourDbContext>(null);
When you create your model the Code first from your EF maps it to your database. It creates hash of the schema which is stored in the EdmMetadata table which is created with database. Existing databases won’t have the EdmMetadata table and so won’t have the has and the implementation will throw if that table is missing.
Or alternatively you can also do the following
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.IncludeMetadataInDatabase = false;
}
in your dbcontext
I just changed my Database in MVC 4 Default sample in Visual Studio 2012.but new database contains all the tables that included Default DB,
I understood few places that should change when we change DB.
These are the changes I did
1.Under "Filter" Folder "InitializeSimpleMembershipAttribute.cs" File
WebSecurity.InitializeDatabaseConnection("HECConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
2.Under Models Folder "AccountModels.cs"
public class UsersContext : DbContext
{
public UsersContext()
: base("HECConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
3.In the Web.config File Connection string
<connectionStrings>
<add name="HECConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=HEC; Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\HEC.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
I like to know rest of the places I should change ?
I'm pretty sure that's all you need, did you try to rebuild your application?
I have a local ASP.NET MVC 3 Windows Azure Project where I use a local instance of MSSQL Express for my emulator.
In my web.config I have the following connection string:
<add name="ExampleDb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ExampleDb;User Instance=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
For debugging purposes I have the following in my WebRole.cs file:
public override bool OnStart()
{
ExampleDb context = new ExampleDb();
context.ExampleItemEntries.Add(new ExampleItem() { ExampleItemId = 1, Att1 = "1", Att2 = "2" });
context.SaveChanges();
return base.OnStart();
}
When I perform this action I can actually see the content in my code-first generated database (using Entity Framework). Database: ExampleDb, Table: ExampleItem.
However, doing the exact same thing in ExampleController does NOT update the database. Instead this data goes somewhere else (I have no idea where). When I visit my controller via the browser I can upload data and look at it but it is not stored in my ExampleDb database, only data sent from WebRole.cs is in the database.
Any ideas what's causing this behaviour?
ExampleDb.cs looks like this:
public class ExampleDb : DbContext
{
public ExampleDb() : base("ExampleDb") { }
public DbSet<ExampleItem> ExampleItemEntries { get; set; }
}
Your connection string contains 'User Instance=True'. This means that SQLEXPRESS uses a user instance to store your data. This is a completely different instance of SQL Server that contains a new set of databases.
I assume the code in WebRole.cs is run in a different user account than the code in ExampleController. When the ExampleController is run under a user account that is not an administrator, a user instance is used...
So when you remove 'User Instance=True' from your connectionstring and assign the proper access rights to your SQLEXPRESS database instance, that would solve the problem.
In CodeFirst Model you should define the connection string in the web.config first as below:
<connectionStrings>
<add name="ExampleDbConnection"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=ExampleDb;
AttachDBFilename=|YouDataDirectory|yourdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
<connectionStrings/>
The DbContext class constructor accepts a name-value pair specifiying connection-string name in web.config. So you can reference this connection string in your context:
class ExampleDb : DbContext
{
public ExampleDb() : base("name=ExampleDbConnection") { }
...
}
This code does work fine in a ASP.NET MVC Web Role so you can try as above.