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?
Related
I use code-first approach and have used SQL Server as database. All the entities are configured like below:
public interface IBaseEntityTypeConfiguration<T>
{
public void Map(EntityTypeBuilder<T> builder);
}
// My entity
public class Student : IBaseEntityTypeConfiguration<Student>
{
public Id { get; set; }
public string Name { get; set; }
public void Map(EntityTypeBuilder<Student> builder)
{
// Configure entity
}
}
In the ApplicationDbContext all the classes which are inherited from IBaseEntityTypeConfiguration are added to the modelBuilder.Configurations.
But I came up with a new requirement. We should switch from SQL Server to PostgreSql!
I don't want to change the Map() method in all entities, but I want to add some kind of provider which says to modelBuilder that use configurations for SQL Server configurations or PostgreSql configs.
Something like below:
public class ApplicationContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// var entities = new MsSqlEntityConfiguration().GetAllTypes();
var entities = new PostgreEntityConfiguration().GetAllTypes();
foreach(entity in entities)
modelBuilder.Configuration.Add(entity); // As an example
}
}
Is there any solution that exists as described?
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 ());
Hi I have server with some databases that have the same schema. I use EF6 Database/Model First code and I do not want to create deterrent DbContext for them. for example my generated DbContext is :
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities()
: base("name=TEST_Rev5_FINALEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Header> tbl_Headers { get; set; }
public virtual DbSet<Output> tbl_Output { get; set; }
public virtual DbSet<Run> tbl_Run { get; set; }
}
and I created a partial class to set the connection string
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities(DbConnection dbConnection)
: base(dbConnection, true)
{
}
}
And I have the following method to create the connection with deterrent connection string:
public DbConnection GetConnectionString()
{
DbConnection conn;
SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = DataSource,
IntegratedSecurity = false,
UserID = User,
Password = Password,
MultipleActiveResultSets = true
};
SqlConnectionFactory sqlConnectionFactory = new SqlConnectionFactory(sqlConnectionStringBuilder.ConnectionString);
conn = sqlConnectionFactory.CreateConnection(DatabaseName);
return conn;
}
Finally I try to run it like this:
using (var context = new TEST_Rev5_FINALEntities(_dal.Connector.GetConnectionString()))
{
return context.tbl_Headers.FirstOrDefault();
}
but I get this error :
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException
HResult=0x80131509 Message=The context is being used in Code First
mode with code that was generated from an EDMX file for either
Database First or Model First development.
How can I do it?
The behavior EF uses depends on the way your connection string looks. If it includes a metadata attribute like this:
metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;
It will presume you are using Database or Model first development.
To make sure Code First is used, remove metadata part of the connection string.
I am getting the error The entity type RelyingParty is not part of the model for the current context even though it exists.
My edmx name is SSO. The edmx is present within Entities folder in Entrada.DAL assembly. Following is the code of SSO.Context class
namespace Entrada.DAL.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class SSOEntities : DbContext
{
public SSOEntities()
: base("name=SSOEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<KeyValuePair> KeyValuePairs { get; set; }
public virtual DbSet<RelyingParty> RelyingParties { get; set; }
}
Following is the connections string in web.config
<add name="SSOEntities" connectionString="metadata=res://*/Entities.SSO.csdl|res://*/Entities.SSO.ssdl|res://*/Entities.SSO.msl;provider=System.Data.SqlClient;provider connection string="data source=dbname;initial catalog=SSO;persist security info=True;user id=user;password=******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This is the code where the error is thrown:
public List<RelyingPartyDALDTO> GetAllRelyingParty()
{
List<RelyingParty> relyingPartDB = DBContext.RelyingParties.ToList();
List<RelyingPartyDALDTO> relyingPartyList = RelyingPartyEntityToDAL.Map<List<RelyingPartyDALDTO>>(relyingPartDB);
return relyingPartyList;
}
DBContext is:
public SSOEntities DBContext
{
get
{
if (SSOEntities == null)
{
SSOEntities = new SSOEntities();
}
return SSOEntities;
}
}
I am getting error on executing the statement:
List relyingPartDB = DBContext.RelyingParties.ToList();
Check the error here
Can you see the error in DBContext? Already existing table(KeyValuePair) does not throw any error but the newly added table RelyingParty throws that error.
I am not understanding what is the problem. For any new table i add to edmx, i am facing this issue.
Can anyone please help me?
Try this in your SSOEntities class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RelyingParty>().ToTable("RelyingParty");
}
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?