Create ConnectionString on fly for SQLite and Entity Framework - c#

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?

Related

Switch Database model EDMX in Entity framework in WPF

I generated EDMX model by Visual studio and i get connection string
<add name="TuttyPOSEntities" connectionString="metadata=res://*/ModelTuttyPOS.csdl|res://*/ModelTuttyPOS.ssdl|res://*/ModelTuttyPOS.msl;provider=Npgsql;provider connection string="Host=localhost;Port=5433;Database=TuttyPOS;Username=postgres"" providerName="System.Data.EntityClient" /></connectionStrings>
public partial class TuttyPOSEntities : DbContext
{
public TuttyPOSEntities()
: base("name=TuttyPOSEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<user> users { get; set; }
}
I need switch between different databases with same schema by connection string in settings file (change provider connection string). How can i do this?

How to check if SQLite Database exists and then create it

I have data in a SQLite Database. But I can not be sure that it will always be there. So when I start my Program I first want to check if the SQLite Database exists and when not I want to create one with the DbSet's I already have in my DbContext.
public class MaintenanceDB : DbContext
{
public MaintenanceDB() : base (new SQLiteConnection(new
SQLiteConnectionStringBuilder { DataSource = "data.sqlite"}.ConnectionString), true)
{
}
public DbSet<MaintenanceEntry> MaintenanceEntries { get; set; }
public DbSet<ModuleEntry> ModuleEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MaintenanceEntry>().ToTable("some Table");
modelBuilder.Entity<ModuleEntry>().ToTable("some Table");
}
}
When I delete my SQLite Database and startup my Program again then I want my SQLite Database to be created.
<connectionStrings>
<add name="MaintenanceDB" connectionString="" providerName="System.Data.SqLite" />
</connectionStrings>
public class MaintenanceDB : DbContext
{
public MaintenanceDB() : base ("Name=MaintenanceDB")
And try the solutions below:
var context = new MaintenanceDB();
if (!context.Database.Exists())
context.Database.Create();
Or
var context = new MaintenanceDB();
context.Database.CreateIfNotExists();
Or create an initializer class as below:
// public class ContentInitializer: DropCreateDatabaseAlways <MaintenanceDB>
// public class ContentInitializer: CreateDatabaseIfNotExists <MaintenanceDB>
public class ContentInitializer: DropCreateDatabaseIfModelChanges <MaintenanceDB>
And put this at the beginning of the application.
Database.SetInitializer (new ContentInitializer ());

How can I have access in membership tables in mvc4?

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

Entity Framework Code First (New Database) Producing Error - "CREATE DATABASE permission denied in database 'master'."

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" />

Specified key was too long; max key length is 767 bytes Mysql error in Entity Framework 6

I have start working on Asp.net Mvc-5 application using visual studio 2012. So I have downloaded Entity Framework-6 and MySQL 6.8.3.0 from nuget. When I tried to create database by using db Context command
dbContext.Database.CreateIfNotExists();
This exception thrown.
Specified key was too long; max key length is 767 bytes
I have done search on it, but cannot find any solution. One thing that I got during my search, this can be Unicode characters problem. I don't know how to deal with this issue.
Updated
I am using following configuration
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
My DB Context class. I have removed all the models just keep left one model
public class MyContext : DbContext
{
public MyContext()
: base("myconn")
{
this.Configuration.ValidateOnSaveEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
public DbSet<ModelOne> ModelOne { get; set; }
}
Model class
public class ModelOne
{
[Key]
public int CreatedId { get; set; }
public Nullable<int> UserId { get; set; }
public Nullable<DateTime> Date { get; set; }
public string Description { get; set; }
}
Can anyone help me with this issue?
Thank you.
I have changed the DbConfigurationType of DbContext.
Got from this this link stackoverflow
Now it is working
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MyContext : DbContext
{
public MyContext()
: base("myconn")
{
this.Configuration.ValidateOnSaveEnabled = false;
}
static MyContext()
{
DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
public DbSet<ModelOne> ModelOne { get; set; }
}
If you're using ASP.NET Identity then there are 3 places where this is happening
In the migration history table
The Name property of IdentityRole
The Username and Email property of ApplicationUser
Most articles I came across has a solution that basically reduce the length of Username and Email to 128 character. However, i found this is unacceptable because the official spec for email address is 256 ansi characters.
My solution was to :
Turn unicode off for Email and Username
override MySqlMigrationSqlGenerator and tell it to use latin1_general_ci collate, which is ansi character set.
reduce the length of role name. This is acceptable as role name doesn't need to be that long
reduce key length for history migration as described in various articles on the Internet.
You can find my solution at https://github.com/timdinhdotcom/MySql.AspNetIdentity
If you have tried all the answers in this post and still getting the error, then try running this command on MySQL server:
set GLOBAL storage_engine='InnoDb';
The bug was reported here: http://bugs.mysql.com/bug.php?id=4541
Use the configuration code below... This solved my problem:
internal sealed class Configuration : DbMigrationsConfiguration<MDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
CommandTimeout = 3600;
DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration());
SetSqlGenerator(MySql.Data.Entity.MySqlProviderInvariantName.ProviderName, new MySql.Data.Entity.MySqlMigrationSqlGenerator());
SetHistoryContextFactory(MySql.Data.Entity.MySqlProviderInvariantName.ProviderName, (connection, schema) => new MySql.Data.Entity.MySqlHistoryContext(connection, schema));
}
}
Take a look at this article and see if it helps. Especially the MySqlHistoryContext.cs, Configuration.cs and MySqlInitializer.cs classes added.
This is where you will find your solution.
public class MySqlHistoryContext : HistoryContext
{
public MySqlHistoryContext(DbConnection connection, string defaultSchema)
: base(connection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}
There are simple way to change NVARCHAR fields to varchar in MYSQl add this lines in IdentityModels.cs
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, int, UserLogin, UserRole, UserClaim>
{
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//troca todos os campos NVARCHAR por varchar
modelBuilder.Properties().Where(x =>
x.PropertyType.FullName.Equals("System.String") &&
!x.GetCustomAttributes(false).OfType<ColumnAttribute>().Where(q => q.TypeName != null && q.TypeName.Equals("varchar(max)", StringComparison.InvariantCultureIgnoreCase)).Any())
.Configure(c =>
c.HasColumnType("varchar(65000)"));
modelBuilder.Properties().Where(x =>
x.PropertyType.FullName.Equals("System.String") &&
!x.GetCustomAttributes(false).OfType<ColumnAttribute>().Where(q => q.TypeName != null && q.TypeName.Equals("nvarchar", StringComparison.InvariantCultureIgnoreCase)).Any())
.Configure(c =>
c.HasColumnType("varchar"));
}
public ApplicationDbContext() : base("DefaultConnection")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
You have to see this link
https://stackoverflow.com/a/27082231/929740
Adding the DbConfigurationTypeAttribute on the context class:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
Calling DbConfiguration.SetConfiguration(new MySqlEFConfiguration()) at the application startup
Set the DbConfiguration type in the configuration file:
< entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
I got rid of this issue by running:
Enable-Migrations -EnableAutomaticMigrations -Force -ContextTypeName ApplicationDbContext
And without creating an Initial migration:
Update-Database
The tables were created without any problem nor errors

Categories

Resources