2

I have DbContext class in order to use migration and create new database or create tables for existing database.

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        #region Tables

        public DbSet<Author> Author { get; set; }

        public DbSet<Books> Books { get; set; }

        #endregion




        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("");
            base.OnConfiguring(optionsBuilder);
        }

    }

LoginController:

  using (var context = new ApplicationDbContext())
  {
   context.Database.Migrate(); // if this code works it gets connection string from appsettings automaticly.How can i change connection string ?
  }

Migration Class:

 [DbContext(typeof(ApplicationDbContext))]
    partial class ApplicationDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
                {
                    b.Property<string>("Id");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Name")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedName")
                        .HasAnnotation("Relational:Name", "RoleNameIndex");

                    b.HasAnnotation("Relational:TableName", "AspNetRoles");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("RoleId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("ClaimType");

                    b.Property<string>("ClaimValue");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("Id");

                    b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
                {
                    b.Property<string>("LoginProvider");

                    b.Property<string>("ProviderKey");

                    b.Property<string>("ProviderDisplayName");

                    b.Property<string>("UserId")
                        .IsRequired();

                    b.HasKey("LoginProvider", "ProviderKey");

                    b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
                {
                    b.Property<string>("UserId");

                    b.Property<string>("RoleId");

                    b.HasKey("UserId", "RoleId");

                    b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
                });

            modelBuilder.Entity("Risklator.Models.ApplicationUser", b =>
                {
                    b.Property<string>("Id");

                    b.Property<int>("AccessFailedCount");

                    b.Property<string>("ConcurrencyStamp")
                        .IsConcurrencyToken();

                    b.Property<string>("Email")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<bool>("EmailConfirmed");

                    b.Property<bool>("LockoutEnabled");

                    b.Property<DateTimeOffset?>("LockoutEnd");

                    b.Property<string>("NormalizedEmail")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("NormalizedUserName")
                        .HasAnnotation("MaxLength", 256);

                    b.Property<string>("PasswordHash");

                    b.Property<string>("PhoneNumber");

                    b.Property<bool>("PhoneNumberConfirmed");

                    b.Property<string>("SecurityStamp");

                    b.Property<bool>("TwoFactorEnabled");

                    b.Property<string>("UserName")
                        .HasAnnotation("MaxLength", 256);

                    b.HasKey("Id");

                    b.HasIndex("NormalizedEmail")
                        .HasAnnotation("Relational:Name", "EmailIndex");

                    b.HasIndex("NormalizedUserName")
                        .HasAnnotation("Relational:Name", "UserNameIndex");

                    b.HasAnnotation("Relational:TableName", "AspNetUsers");
                });

            modelBuilder.Entity("Risklator.Models.CompanyDBModel.Author", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("AuthorID");

                    b.Property<string>("FirstMidName");

                    b.Property<string>("LastName")
                        .IsRequired();

                    b.HasKey("Id");
                });

            modelBuilder.Entity("Risklator.Models.CompanyDBModel.Books", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int>("AuthorID");

                    b.Property<int>("BookID");

                    b.Property<string>("Genre");

                    b.Property<decimal>("Price");

                    b.Property<string>("Title")
                        .IsRequired();

                    b.Property<int>("Year");

                    b.HasKey("Id");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
                {
                    b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
                        .WithMany()
                        .HasForeignKey("RoleId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
                {
                    b.HasOne("Risklator.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
                {
                    b.HasOne("Risklator.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId");
                });

            modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
                {
                    b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
                        .WithMany()
                        .HasForeignKey("RoleId");

                    b.HasOne("Risklator.Models.ApplicationUser")
                        .WithMany()
                        .HasForeignKey("UserId");
                });

            modelBuilder.Entity("Risklator.Models.CompanyDBModel.Books", b =>
                {
                    b.HasOne("Risklator.Models.CompanyDBModel.Author")
                        .WithMany()
                        .HasForeignKey("AuthorID");
                });
        }
    }

Question:

Is it possible to set connection string to optionsBuilder.UseSqlServer(""); by using session in asp.net mvc 6 as below ?

optionsBuilder.UseSqlServer(HttpContext.Session.GetString("connectionString"))

Thanks

Soner
  • 1,280
  • 3
  • 16
  • 40
  • 1
    Do you have different connection string or you need to connect to two different databases? – Vova Bilyachat Mar 04 '16 at 10:05
  • yes i have different connecttionstring from database.If a customer logins to system i get connection string from database than i need to connect for customer database.I am not sure how can i connect db dynamically thanks – Soner Mar 04 '16 at 10:08

1 Answers1

1

I am not sure if it would help since i will write solution for EF 6. But in entityframework 6 you can pass connection string name or connection string to constructor when you create context object.

If you are using dependency injection it would be better to do it there when you contruct object

Here is actually example how to do that with EF 7

You mentioned about migrations, well again i am not sure about EF7 but in EF6 there is DBMigrator.

 DbMigrationsConfiguration configuration = new DbMigrationsConfiguration()
{
    MigrationsAssembly = typeof(YOURASSEMBLY).Assembly,
    ContextType = typeof(YOURASSEMBLY),
    TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(__YOUR_CONNECTION_STRING__)
};

DbMigrator dbMigrator = new DbMigrator(configuration);
dbMigrator.Update();

So you would need to create cycle to update all you dbs on app start or console app. Depends on your setup.

PS. In EF7 its even easier look here

Community
  • 1
  • 1
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
  • thanks for your answer.However if i use constructor method i can not migration how can i solve this problem ? – Soner Mar 04 '16 at 10:13
  • @SonerSevinc Does it helps? – Vova Bilyachat Mar 04 '16 at 11:04
  • i am using ef7.If i try code from link that you have posted it is not working because i am using IdentityDbContext inheritance in dbcontext.if i inheritance IdentityDbContext it automaticly searchs connection string from appsettings. This is not what i need. – Soner Mar 04 '16 at 12:02
  • @SonerSevinc have checked link to EF7 documentation which i posted? – Vova Bilyachat Mar 04 '16 at 12:03
  • i checked your link thanks for your answer.Please check my question again.I added LoginController.I make migration over there in order to create database tables.However problem about default connecttion string.How can i change connection string acording to my code in question ? Please also check [DbContext(typeof(ApplicationDbContext))] in my question.This gets connection string default. – Soner Mar 04 '16 at 12:06
  • Sonor, did you resolve this? I need to perform the same action. I need to dynamically point to the client application's database. – Nate Aug 03 '17 at 14:50