I am trying to use register and login form in MVC4 . I have used Entity Framework from DB to create the model and now I want to generate the membership tables, but I have tried many things and I still can't access them.
I have 2 connection strings :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Projekti-20160917211151.mdf" providerName="System.Data.SqlClient" />
<add name="UniversitetiEntities" connectionString="metadata=res://*/Models.Universiteti.csdl|res://*/Models.Universiteti.ssdl|res://*/Models.Universiteti.msl;provider=System.Data.SqlClient;provider connection string="data source=ARBERS-PC\BERSANTA;initial catalog=Universiteti;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
In Account Model I changed the base in UniversitetiEntities :
public class UsersContext : DbContext
{
public UsersContext()
: base("UniversitetiEntities")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
I Also did this chang in InitializeSimpleMembershipAttribute file:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("UniversitetiEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
but it always throws this exception : The ASP.NET Simple Membership database could not be initialized.
AFAIK, SimpleMembershipProvider user profile management only works with SQL Server database connection string, not an EF connection string.
First, try setting your DB connection string instead of EF-generated connection string as stated here:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
// also set your DB connection string on current DB context
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
If the first solution won't work, try removing AttachDbFileName property from SQL Server connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
NB: If your DB connection has certain user ID & password to get access, include them in DefaultConnection.
Depending on your EF model generation (code first, database first or model first approach), you can set autoCreateTables: by true or false based from existence of UserProfile table.
Further information: SimpleMembership Provider Reference
Related
I want to use the Scaffolding Mechanism in the Entity Framework to create a MusicDBContext database and table automatically, but a problem occurred when I was programming.
The creation of steps shown below:
1. Create a console application.
2. Use the NuGet to install the Entity Framework: PM> install-package Entity Framework
3. Insert the following code into the configuration Session in App.Config:
<connectionStrings>
<add name="MusicDBContext"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
Initial Catalog=MusicDBContext;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\MusicDBContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
4. Write the following code in the console:
using System;
using System.Linq;
using System.Data.Entity;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
MusicDbContext db = new MusicDbContext();
Music music = new Music { Title = "Far Away From Home",
ReleaseDate = DateTime.Now };
db.Musics.Add(music);
db.SaveChanges();
db.Musics.ToList().ForEach(x => Console.WriteLine($"{x.ID},
{x.Title},{x.ReleaseDate}"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if(ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
Console.ReadKey();
}
}
public class Music
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { set; get; }
}
public class MusicDbContext : DbContext
{
public MusicDbContext() : base("MusicDBContext") { }
public DbSet<Music> Musics { set; get; }
}
}
However, the following error occurred during runtime:
A file activation error occurred.
The physical file name '\\MusicDBContext.mdf' may be incorrect.
Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created.
Check related errors.
When I delete all the content in the connectionStrings session, it runs OK.
Entity Framework uses the default connection of SqlLocalDB.
ConnectionString shown below:
Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MusicDBContext;Integrated Security=True;MultipleActiveResultSets=True
Why is there a problem with the connection named MusicDBContext?
The keyword DataDirectory has problem?
I am owndering about a way to create a ConnectionString on fly for SQLite and Entity Framework (MS VS2015, MS .NET Framework 4.5.6).
I mean the application gets some databases connectionstring and choose one of them.
Basically I would like to do it here
MyAppEntities context = new MyAppEntities();
The class itself looks like
public partial class MyAppEntities : DbContext
{
public MyAppEntities ()
: base("name=MyAppEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Commands> Commands { get; set; }
public virtual DbSet<Errors> Errors { get; set; }
}
Also I would like to know if possible to use relative path for SQLite here
<connectionStrings>
<add name="MyAppEntities " connectionString="metadata=res://*/DatabaseModel.AgentDataModel.csdl|res://*/DatabaseModel.AgentDataModel.ssdl|res://*/DatabaseModel.AgentDataModel.msl;provider=System.Data.SQLite.EF6;provider connection string="data source=D:\Databases\MyAgent.db""
providerName="System.Data.EntityClient" />
<add name="MyAppAgent.Properties.Settings.MyAppAgentConnectionString"
connectionString="data source=D:\Databases\MyAgent.db"
providerName="System.Data.SQLite.EF6" />
</connectionStrings>
Any clue how it can be done?
Im trying to create a database called Todo with Entity Framework. I want this database to appear in Sql Server Managment after It has been created.
I have the context file:
namespace Domain
{
//Associate the model with the database
//This class then automatically defines a property for each table in the database that I want to work with.
public class EFDbContext : DbContext
{
public EFDbContext() : base("EFDbContext")
{
}
public DbSet<List> Lists { get; set; }
public DbSet<Task> Tasks { get; set; }
}
}
I have my Initilizer:
namespace Domain
{
public class ListRepository : System.Data.Entity.DropCreateDatabaseIfModelChanges<EFDbContext>
{
protected override void Seed(EFDbContext context)
{
var todo = new List<List>
{
new List { Day="MÃ¥nadg" },
new List { Day="Tisdag" },
new List { Day="Onsdag" },
new List { Day="Torsdag" },
new List { Day="Fredag" }
};
todo.ForEach(t => context.Lists.Add(t));
context.SaveChanges();
}
}
}
And here I have my Web.Config:
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Todo;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<contexts>
<context type="todo.domain.EFDbContext, todo">
<databaseInitializer type="todo.domain.ListRepository, todo"></databaseInitializer>
</context>
</contexts>
When I run my application, I Data Connections Is created In Server Explorer as In the picture below:
When I click on this Data Connection, I get the following error message:
When I check In Sql Server Managment, no Database Is listed there.
What am I doing wrong here? Why Is not the dabatabase created?
As you can see, I have a solution called Todo, and In the Todo-solution, I have three projects. I have the DbContext In the Domain-project
From your screenshot, it says login failed for user Bryan in your message. This would mean Bryan is unable to connect
Check the following 3 items
From your Sql Management studio, open the Db, right icons and scroll down to security, (in windows authentication mode, usually easiest) and scroll down to security and then add Bryan as a user giving him DBO rights
Authentication type Check is Mixed Mode authentication is enabled
Switch the connection to Authentication and try with SA role
I have created a new project (ASP.NET MVC) that will use Entity Framework Code First to create a new Database and add records to the database one time only and populate a drop down.
I am trying to figure out how to generate the database automatically. So far, when I run the code I get "CREATE DATABASE permission denied in database 'master'.". Master is not the correct database. What would I need to modify in my code or connection string to create the database automatically from scratch?
Controller:
namespace TDReport.Controllers
{
public class ReportController : Controller
{
//
// GET: /Report/
public ActionResult Index()
{
var db = new StageContext();
if (!db.Database.Exists())
{
db.Database.Create();
db.Stages.Add(new Stage { PCR = 201 });
db.Stages.Add(new Stage { PCR = 202 });
db.Stages.Add(new Stage { PCR = 203 });
db.Stages.Add(new Stage { PCR = 501 });
db.SaveChanges();
}
return View();
}
Context Class:
namespace TDReport.Models
{
public class StageContext : DbContext
{
public DbSet<Stage> Stages { get; set; }
public DbSet<Report> Reports {get; set;}
}
}
Model:
namespace TDReport.Models
{
public class Stage
{
public int ID { get; set; }
public int PCR { get; set; }
}
}
Connection String Tags:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TDReport-20140825134744;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TDReport-20140825134744.mdf" />
<add name="StageProductionEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StageProduction.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
You need to have a connection string that matches the name of db context if you have parameterless constructor in the db context.
<add name="StageContext" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial
Catalog=TheDatabaseName;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\TheDatabaseName.mdf" />
I have entity framework 5 with the mysql connector installed (mysql for vs 1.1.3 and mysql connector 6.8.3) and have a connection string in my app.config:
<add name="applicantDBEntities" connectionString="metadata=res://*/Models.applicantsDBModel.csdl|res://*/Models.applicantsDBModel.ssdl|res://*/Models.applicantsDBModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=root;database=applicantsdb"" providerName="System.Data.EntityClient" />
If I use the connection string in the app.config, everything works, but I want the user to be able to choose his server, username, password and DB. How i tried to implement it:
public partial class applicantDBEntities : DbContext
{
public applicantDBEntities()
: base("name=applicantDBEntities")
{
}
public applicantDBEntities(string connectionString) : base (connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<applicant> applicants { get; set; }
public DbSet<file> files { get; set; }
}
And the initialization itself:
CONNECTION_PATTERN = "server={0};database={1};User Id={2};password={3}";
this.dbContext = new applicantDBEntities(String.Format(CONNECTION_PATTERN,
Settings.GetInstance().Server, Settings.GetInstance().Database,
Settings.GetInstance().User, Settings.GetInstance().Password));
but no matter what I pass as arguments (even wrong ones) I always end up in the OnModelCreating method.
What is the correct way to do this?
EDIT:
As #Andrew mentioned, my connection string was wrong. This is how I do it now:
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = "res://*",
Provider = "MySql.Data.MySqlClient",
ProviderConnectionString = new System.Data.SqlClient.SqlConnectionStringBuilder
{
InitialCatalog = Settings.GetInstance().Database,
DataSource = Settings.GetInstance().Server,
IntegratedSecurity = false,
UserID = Settings.GetInstance().User,
Password = Settings.GetInstance().Password
}.ConnectionString
}.ConnectionString;
this.dbContext = new applicantDBEntities(connectionString);
Your connection string is in invalid format.
It should resemble this:
"metadata=res://*/Northwind.csdl|
res://*/Northwind.ssdl|
res://*/Northwind.msl;
provider=System.Data.SqlClient;
provider connection string=
"Data Source=.\sqlexpress;
Initial Catalog=Northwind;
Integrated Security=True;
MultipleActiveResultSets=True""
and might be based on EntityConnectionStringBuilder
http://msdn.microsoft.com/en-us/data/jj592674.aspx here's description of how you should connect to database for different scenarios and framework versions