locked
Store the Controllers name and Actions Name into my Custom Tables that I Add them into Identity in CodeFirst Asp.Net MVC Project RRS feed

  • Question

  • User618483968 posted

    Seniors, <br/>
    I'm using ASP.NET Identity on my ASP.Net web application and I Add my custom Tables(with their relations) to Identity on my CodeFirst ASP.Net MVC Project.when I Run Project for the first time,the databace is created automatically with the custom tables and relations between them in SqlServer. <br/>
    Custom Tables :

    1. MvcControllers
    2. ActionsTbls
    3. GroupsTbls
    4. AspNetUser_Action
    5. AspNetUser_Group
    6. Action_Group

    * This is The Diagram of my Database Image :Database Diagram Click Here

    For Creating Custom tables,I Add Some Codes to IdentityModels.cs. <br/>
    IdentityModels.cs :

    namespace Admin_Base_SN.Models
    {
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    return userIdentity;
    }
    public virtual AspNetUser_Action AspNetUser_Action { get; set; }

    public virtual AspNetUser_Group AspNetUser_Group { get; set; }

    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {


    public DbSet<MvcController> MvcController { get; set; }
    public DbSet<ActionsTbls> ActionsTbls { get; set; }
    public DbSet<AspNetUser_Action> AspNetUser_Actions { get; set; }

    public DbSet<GroupsTbl> GroupsTbls { get; set; }
    public DbSet<Action_Group> Action_Groups { get; set; }

    public DbSet<AspNetUser_Group> AspNetUser_Groups { get; set; }
    public ApplicationDbContext()
    : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

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

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    base.OnModelCreating(modelBuilder);

    // one-to-zero or one relationship between ApplicationUser and Customer
    // UserId column in Customers table will be foreign key
    modelBuilder.Entity<ApplicationUser>()
    .HasOptional(m => m.AspNetUser_Action)
    .WithRequired(m => m.ApplicationUser)
    .Map(p => p.MapKey("AspNetUser_Id"));

    modelBuilder.Entity<ApplicationUser>()
    .HasOptional(m => m.AspNetUser_Group)
    .WithRequired(m => m.ApplicationUser)
    .Map(p => p.MapKey("AspNetUser_Id"));

    }

    }
    }


    What I want <br/>
    At first,I want to save All the Controllers Names and Actions Names of Project into separated Lists,then insert them into MvcController Table & ActionsTbl Table.This process should be done automatically when I Run Project for the first time.I mean When the Database is Created, the Lists inert to their tables automatically.

    * I think it's better to Add a New Custom Function to the Identity for inserting Lists to the Tables.

    I appreciate your efforts in reaching a solution for my problem.

    Monday, January 22, 2018 5:57 AM

Answers

All replies

  • User1564875471 posted

    You need to create a custom EF initializer for your context, and override it's seed method to tell it how you want to fill the database.

    see here some guides:

    http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx

    http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 22, 2018 9:57 AM
  • User-832373396 posted

    Hi asakhaei871,

    At first<g class="gr_ gr_50 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="50" data-gr-id="50">,I</g> want to save All the Controllers Names and Actions Names of Project into separated Lists<g class="gr_ gr_51 gr-alert gr_gramm gr_inline_cards gr_run_anim Style replaceWithoutSep" id="51" data-gr-id="51">,then</g> insert them into MvcController Table & ActionsTbl Table.This process should be done automatically when I Run Project for the first time.

    Sir, I guess that you want to get  Controllers Names from all class name or  Actions Names from all method name from .dll file dynamic and insert them when starting the project at the first time.

    if so, System.Reflection is what you need ,it could get class information from .dll file.

    and the generic code looks like:

    public class WebApiApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                Assembly asm = Assembly.GetExecutingAssembly();
                //asm:  WebApiApplication , Version=1.0.0.0, Culture=neutral, PublicKeyToken=null}
                List<string> namespacelist = new List<string>();
                List<string> classlist = new List<string>();
    
           ApplicationDbContext db = new ApplicationDbContext();
    
                foreach (Type type in asm.GetTypes())
                {
                     //Debug.WriteLine("namespace name:" + type.Namespace);
                    if (type.Namespace!=null&& type.Namespace.Contains("Controllers"))
                    {
                        //Debug.WriteLine("namespace name which controllers foloder :" + type.Namespace);               
    
                         if (type.Name.Contains("Controller")) {
       // do add operation
                            Debug.WriteLine("class name which contains Controller :" + type.Name);
                            //getMethodList(type);
                            System.Reflection.MethodInfo[] methods = type.GetMethods();
    
                            foreach (System.Reflection.MethodInfo method in methods)
                            {
                                if (method.Name.Contains("get_")) {
                                    break;
                                }
                                Debug.WriteLine("method Name:" + method.Name);                     
     // do add operation
                            }
                        }
    
                    }
                }            
            }

    Output result:

    class name which contains Controller :DefaultController
    method Name:Index
    class name which contains Controller :EasyModelsController
    method Name:Index
    method Name:Details
    method Name:Create
    method Name:Upload
    method Name:Create
    method Name:Edit
    method Name:Edit
    method Name:Delete
    method Name:DeleteConfirmed
    class name which contains Controller :ProfilesController
    method Name:Index
    method Name:Details
    method Name:Create
    method Name:Create
    method Name:Edit
    method Name:Edit
    method Name:Delete
    method Name:Delete
    class name which contains Controller :HomeController
    method Name:GetA
    method Name:CreatE
    method Name:CreateBar
    method Name:Index
    method Name:InsertItemLastFair
    method Name:Index1
    method Name:Index2
    class name which contains Controller :ValuesController
    method Name:Get
    method Name:Get
    method Name:Post
    method Name:Put
    method Name:Delete

    Guide

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection  

    With regards, Angelina Jolie

    Monday, January 29, 2018 10:10 AM