locked
How to Integrating ASP.NET Identity into Existing DbContext RRS feed

  • Question

  • User264732274 posted

    i want identity should use my own DB context instead of its own. please guide me how to do it.

    i want single db context through out the project. guide me how it will be possible ?

    sample identity db context

    public class ApplicationDbContext : IdentityDbContext
        {    
            public ApplicationDbContext(): base("DefaultConnection")
            {
            }
    
            protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<IdentityUser>().ToTable("user");
                modelBuilder.Entity<ApplicationUser>().ToTable("user");
    
                modelBuilder.Entity<IdentityRole>().ToTable("role");
                modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
                modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
                modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
            }
        }

    thanks

    Tuesday, November 15, 2016 8:34 AM

Answers

  • User283571144 posted

    Hi sudip_inn,

    Sorry still this concept is not clear IdentityDbContext<BusinessAccount>
    why we need to mention BusinessAccount name here because i must have other entity classes then why we are not specify their name with in <> ?

    I used custom user IdentityUser class.

    I add four table in this class, "RepFirstName", "RepLastName", "Title", "JoinDate".

    If you don't need to use custom user table, you just need to make your dbcontext inherit IdentityDbContext.

    Like below:

    public ApplicationDbContext() : IdentityDbContext
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }

    what is the meaning of this line throwIfV1Schema:
    false ?


    This means it will determine whether to throw an exception if the schema matches that of Identity 1.0.0.

    We will set this value to false, so it will not throw an exception if the schema matches that of Identity 1.0.0.

    see my db context and there is no any create function but your db context has........why
    Create() is required ?

    This is used to easily create ApplicationDbContext in the codes, not required.

    All my codes is used with IdentityConfig by add webform auto generated.

    If you just need to add identity to your application, you could refer to follow codes:

    [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
        }
    
        public class ApplicationDbContext : IdentityDbContext
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString")
            {
            }
            public DbSet<Sector> Sectors { get; set; }
        }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 18, 2016 1:44 AM
  • User283571144 posted

    Hi sudip_inn,

    when i click on this link then got this text.

    The link maybe expired, please try again.

    Link:https://1drv.ms/u/s!At8k4dll_NA7gnOU0wzXYrmq8Jd-

    Note:I don't upload my sqldatabase, please changed the webconfig connection string by yourself.

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 28, 2016 1:47 AM

All replies

  • User264732274 posted

    few relevant links for the issue

    http://stackoverflow.com/questions/21418902/integrating-asp-net-identity-into-existing-dbcontext
    http://stackoverflow.com/questions/20002539/using-same-dbcontext-for-identity-and-other-db-entities
    http://stackoverflow.com/questions/36367976/merging-asp-net-identity-dbcontext-with-my-dbcontext
    http://odetocode.com/blogs/scott/archive/2014/01/03/asp-net-identity-with-the-entity-framework.aspx
    https://forums.asp.net/t/2002296.aspx?DBContext+VS+IdentityDBContext
    https://blogs.msdn.microsoft.com/webdev/2013/10/20/building-a-simple-todo-application-with-asp-net-identity-and-associating-users-with-todoes/

    Tuesday, November 15, 2016 12:42 PM
  • User-691209617 posted

    Hi Sir,

    You can create a static class and pass it to db context class. In my case I get connection from db dynamically. please see the code

    public CompanyEntities(long companyid)
                : base(GetConnectionString(companyid))
            {
            }
            private static string GetConnectionString(long companyid)
            {
                domain_settings settings;
                using (var context = new CondadoMediaVault())
                {
                    settings = context.domain_settings.FirstOrDefault(x => x.set_cmp_key == companyid);
                }
    
                string connstring = settings.set_connection_string;
                //SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
                //sqlBuilder.DataSource = "ds-development";
                //sqlBuilder.InitialCatalog = "Condado_MediaVault_Condado3";
                //sqlBuilder.UserID = "condado";
                //sqlBuilder.Password = "@Password1";
                //sqlBuilder.PersistSecurityInfo = true;
                //sqlBuilder.IntegratedSecurity = false;
                //sqlBuilder.MultipleActiveResultSets = true;
    
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
                //entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
                entityBuilder.ProviderConnectionString = connstring.ToString();
                entityBuilder.Metadata = "res://*/Model.CompanyModel.csdl|res://*/Model.CompanyModel.ssdl|res://*/Model.CompanyModel.msl";
                entityBuilder.Provider = "System.Data.SqlClient";
    
                return entityBuilder.To

    Well you can modify it for general purpose too

    public class ApplicationDbContext : IdentityDbContext
        {    
            public ApplicationDbContext(string Connstring): base(Connstring)
            {
            }
    
    
             private static string GetConnectionString(string Connstring)
            {
                
    
                string connstring = Connstring;// get from db or web.config
                //SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
                //sqlBuilder.DataSource = "ds-development";
                //sqlBuilder.InitialCatalog = "Condado_MediaVault_Condado3";
                //sqlBuilder.UserID = "condado";
                //sqlBuilder.Password = "@Password1";
                //sqlBuilder.PersistSecurityInfo = true;
                //sqlBuilder.IntegratedSecurity = false;
                //sqlBuilder.MultipleActiveResultSets = true;
    
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
                //entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
                entityBuilder.ProviderConnectionString = connstring.ToString();
                entityBuilder.Metadata = "res://*/Model.CompanyModel.csdl|res://*/Model.CompanyModel.ssdl|res://*/Model.CompanyModel.msl";
                entityBuilder.Provider = "System.Data.SqlClient";
    
                return entityBuilder.ToString();
            }
        }

    Hope it helps.

    Tuesday, November 15, 2016 1:13 PM
  • User264732274 posted

    sorry that i could get the things properly after seeing your code. where is local db context ?

    please provide small but full complete sample code to merge identity into existing db context.

    thanks

    Tuesday, November 15, 2016 1:30 PM
  • User-691209617 posted

    Please use this

    public class ApplicationDbContext : IdentityDbContext
        {    
            public ApplicationDbContext(string Connstring): base(Connstring)
            {
            }
    
    
             private static string GetConnectionString(string Connstring)
            {
                
    
                string connstring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
               
    
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
               
                entityBuilder.ProviderConnectionString = connstring.ToString();
                entityBuilder.Metadata = "res://*/Model.CompanyModel.csdl|res://*/Model.CompanyModel.ssdl|res://*/Model.CompanyModel.msl";
                entityBuilder.Provider = "System.Data.SqlClient";
    
                return entityBuilder.ToString();
            }
        }

    This is working code and it works for me.

    Tuesday, November 15, 2016 1:40 PM
  • User283571144 posted

    Hi sudip_inn,

    i want identity should use my own DB context instead of its own. please guide me how to do it.

    i want single db context through out the project. guide me how it will be possible ?

    According to your description, I suggest you could change your own dbcontext inherit IdentityDbContext.

    Then you could add a custom applicationuser class inherit IdentityUser class.

    More details, you could refer to follow codes sample:

    Default Dbcontext:

    [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
        }
    
        [Table("TRACS.Lookup_Campus")]
        public class Campus
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Campus Id", AutoGenerateField = true)]
            public int Campus_Id { get; set; }
    
            [Required]
            [StringLength(20)]
            public string Campus_Name { get; set; }
    
            [Required]
            public Boolean Active { get; set; }
    
            [Required]
            [ForeignKey("Sector")]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public int Sector_Id { get; set; }
    
            [Display(Name = "Sector", AutoGenerateField = true)]
            public virtual Sector Sector { get; set; }
        }
    
    public class ApplicationDbContext :DbContext
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString")
            {
            }
    
            public DbSet<Sector> Sectors { get; set; }
    
            public DbSet<Campus> Campuss { get; set; }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
    

    After update-database:

    Result:

    Add identity:

     [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
        }
    
        [Table("TRACS.Lookup_Campus")]
        public class Campus
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Campus Id", AutoGenerateField = true)]
            public int Campus_Id { get; set; }
    
            [Required]
            [StringLength(20)]
            public string Campus_Name { get; set; }
    
            [Required]
            public Boolean Active { get; set; }
    
            [Required]
            [ForeignKey("Sector")]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public int Sector_Id { get; set; }
    
            [Display(Name = "Sector", AutoGenerateField = true)]
            public virtual Sector Sector { get; set; }
        }
        public class BusinessAccount : IdentityUser
        {
           
            public string RepFirstName { get; set; }
     
            public string RepLastName { get; set; }
    
            public string Title { get; set; }
      
            public DateTime JoinDate { get; set; }
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<BusinessAccount> manager, string authenticationType)
            {
                var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
                // Add custom user claims here
                return userIdentity;
            }
        }
    
        public class ApplicationDbContext : IdentityDbContext<BusinessAccount>
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }
    
            public DbSet<Sector> Sectors { get; set; }
    
            public DbSet<Campus> Campuss { get; set; }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }

    Result:

    Best Regards,

    Brando

    Wednesday, November 16, 2016 8:15 AM
  • User264732274 posted

    @Brando thanks for the reply.

    i want to merge these two below class into single one class....just tell me how could i do this ?

    public class ApplicationDbContext : IdentityDbContext<BusinessAccount>
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }
    
            public DbSet<Sector> Sectors { get; set; }
    
            public DbSet<Campus> Campuss { get; set; }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
    
    AND
    
    public class ApplicationDbContext :DbContext
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString")
            {
            }
    
            public DbSet<Sector> Sectors { get; set; }
    
            public DbSet<Campus> Campuss { get; set; }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }

    Wednesday, November 16, 2016 9:28 AM
  • User283571144 posted

    Hi sudip_inn,

    i want to merge these two below class into single one class....just tell me how could i do this ?

    This codes is all in one class and working well.

     [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
        }
    
        [Table("TRACS.Lookup_Campus")]
        public class Campus
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Campus Id", AutoGenerateField = true)]
            public int Campus_Id { get; set; }
    
            [Required]
            [StringLength(20)]
            public string Campus_Name { get; set; }
    
            [Required]
            public Boolean Active { get; set; }
    
            [Required]
            [ForeignKey("Sector")]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public int Sector_Id { get; set; }
    
            [Display(Name = "Sector", AutoGenerateField = true)]
            public virtual Sector Sector { get; set; }
        }
        public class BusinessAccount : IdentityUser
        {
           
            public string RepFirstName { get; set; }
     
            public string RepLastName { get; set; }
    
            public string Title { get; set; }
      
            public DateTime JoinDate { get; set; }
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<BusinessAccount> manager, string authenticationType)
            {
                var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
                // Add custom user claims here
                return userIdentity;
            }
        }
    
        public class ApplicationDbContext : IdentityDbContext<BusinessAccount>
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }
    
            public DbSet<Sector> Sectors { get; set; }
    
            public DbSet<Campus> Campuss { get; set; }
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }

    Best Regards,

    Brando

    Wednesday, November 16, 2016 9:52 AM
  • User264732274 posted

    why we need to say the name business account here like IdentityDbContext<BusinessAccount>

    just see my dbcontext code how it look like

    public class TestDBContext : DbContext
    {
    	public TestDBContext()
    	    : base("name=TestDBContext")
    	{
    
    	}
    
    	protected override void OnModelCreating(DbModelBuilder modelBuilder)
    	{
    	    //modelBuilder.Configurations.Add(new vwCustomerConfiguration());
    	    Database.SetInitializer<TestDBContext>(null);
    	}
    
    	public DbSet<Customer> Customer { get; set; }
    	public DbSet<Addresses> Addresses { get; set; }
    	public DbSet<Contacts> Contacts { get; set; }
    	public virtual DbSet<vwCustomer> vwCustomers { get; set; }
    	public DbSet<vwMyCustomers> vwMyCustomers { get; set; }
    }

    see TestDBContext : DbContext here i have not mention any entity name. guide me further. thanks

    Wednesday, November 16, 2016 12:55 PM
  • User283571144 posted

    Hi sudip_inn,

    sudip_inn

    see TestDBContext : DbContext here i have not mention any entity name. guide me further. thanks

    As far as I know, if you want to integrate ASP.NET Identity into Existing DbContext.

    You need to make your dbcontext inherit IdentityDbContext.

    See IdentityDbContext definition:

    Represents a generic IdentityDbContext base that can be customized with entity types that extend from the base IdentityUserXXX types.

    This means if you inherit IdentityDbContext, it will automatic generate the user table, role table and so on.

    Then see its syntax:

    public class IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : DbContext
    where TUser : IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim>
    where TRole : IdentityRole<TKey, TUserRole>
    where TUserLogin : IdentityUserLogin<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserClaim : IdentityUserClaim<TKey>

    You will find IdentityDbContext also inherit DbContext.

    So you just make your DbContext inherit IdentityDbContext.

    That means your own DbContext also inherit EF DbContext.

    More details, you could refer to follow link:

    https://msdn.microsoft.com/en-us/library/dn468176(v=vs.108).aspx

    https://msdn.microsoft.com/en-us/library/dn613255(v=vs.108).aspx

    Best Regards,

    Brando
     

    Thursday, November 17, 2016 1:44 AM
  • User264732274 posted

    Sorry still this concept is not clear IdentityDbContext<BusinessAccount>

    why we need to mention BusinessAccount name here because i must have other entity classes then why we are not specify their name with in <> ?

    public ApplicationDbContext()
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }

    what is the meaning of this line throwIfV1Schema: false ?

    also see this line

    public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }

    see my db context and there is no any create function but your db context has........why Create() is required ?

    please guide me.

    Thursday, November 17, 2016 8:02 AM
  • User283571144 posted

    Hi sudip_inn,

    Sorry still this concept is not clear IdentityDbContext<BusinessAccount>
    why we need to mention BusinessAccount name here because i must have other entity classes then why we are not specify their name with in <> ?

    I used custom user IdentityUser class.

    I add four table in this class, "RepFirstName", "RepLastName", "Title", "JoinDate".

    If you don't need to use custom user table, you just need to make your dbcontext inherit IdentityDbContext.

    Like below:

    public ApplicationDbContext() : IdentityDbContext
                : base("MySQLConnectionString", throwIfV1Schema: false)
            {
            }

    what is the meaning of this line throwIfV1Schema:
    false ?


    This means it will determine whether to throw an exception if the schema matches that of Identity 1.0.0.

    We will set this value to false, so it will not throw an exception if the schema matches that of Identity 1.0.0.

    see my db context and there is no any create function but your db context has........why
    Create() is required ?

    This is used to easily create ApplicationDbContext in the codes, not required.

    All my codes is used with IdentityConfig by add webform auto generated.

    If you just need to add identity to your application, you could refer to follow codes:

    [Table("TRACS.Lookup_Sector")]
        public class Sector
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            [Display(Name = "Sector Id", AutoGenerateField = true)]
            public int Sector_Id { get; set; }
    
            [Required]
            [StringLength(30)]
            [Display(Name = "Sector Name", AutoGenerateField = true)]
            public string Sector_Name { get; set; }
    
            [Required]
            [Display(Name = "NoDisplay", AutoGenerateField = false)]
            public Boolean Active { get; set; }
        }
    
        public class ApplicationDbContext : IdentityDbContext
        {
            public ApplicationDbContext()
                : base("MySQLConnectionString")
            {
            }
            public DbSet<Sector> Sectors { get; set; }
        }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 18, 2016 1:44 AM
  • User264732274 posted

    can u tell me any url from where i can download source code and run in my pc which has done the same job.

    Friday, November 18, 2016 8:03 AM
  • User283571144 posted

    Hi sudip_inn,

    can u tell me any url from where i can download source code and run in my pc which has done the same job.

    You could download it from below url:

    https://1drv.ms/u/s!At8k4dll_NA7gnOU0wzXYrmq8Jd-

    Best Regards,

    Brando

    Thursday, November 24, 2016 3:28 AM
  • User264732274 posted

    when i click on this link then got this text.

    This item might not exist or is no longer available

    This item might have been deleted, expired, or you might not have permission to view it. Contact the owner of this item for more information.

    Thursday, November 24, 2016 9:29 AM
  • User283571144 posted

    Hi sudip_inn,

    when i click on this link then got this text.

    The link maybe expired, please try again.

    Link:https://1drv.ms/u/s!At8k4dll_NA7gnOU0wzXYrmq8Jd-

    Note:I don't upload my sqldatabase, please changed the webconfig connection string by yourself.

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 28, 2016 1:47 AM
  • User264732274 posted

    i will check your code and if any confusion occur to understand it then i will communicate with you. thanks

    Monday, November 28, 2016 8:39 AM