none
Get model type by name RRS feed

  • Question

  • Dear friends,

    I have this model class:

    namespace gicaic_ws.models
    {
        public class modelos_cab
        {
            public string style { get; set; }
            public string style_customer { get; set; }
            public string season { get; set; }
            public string season_description_pt { get; set; }
        }
    
        public class modelos_lin
        {
            public string style { get; set; }
            public string colour_code { get; set; }
            public string colour_code_customer { get; set; }
            public string barcode { get; set; }
            public string description1_pt { get; set; }
        }
    }


    And I'm creating the object and adding using this method:

    using (DataTable dt = new DataTable())
                        using (SqlConnection cn = new SqlConnection(tools_ws.get_connection_string()))
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            if (cn.State == ConnectionState.Closed) cn.Open();
                            cmd.Connection = cn;
                            cmd.CommandText += "";
                            using (SqlDataAdapter da = new SqlDataAdapter(cmd)) da.Fill(dt);
                            List<models.modelos_cab> m = new List<models.modelos_cab>(); //ALTERAR O MODEL ***********
    
                            var c_names = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName.ToLower()).ToList();
                            var p = typeof(models.modelos_cab).GetProperties(); //ALTERAR O MODEL ***********
                            m = dt.AsEnumerable().Select(row =>
                            {
                                var o = Activator.CreateInstance<models.modelos_cab>(); //ALTERAR O MODEL ***********
                                foreach (var pr in p) if (c_names.Contains(pr.Name.ToLower())) try { pr.SetValue(o, row[pr.Name]); } catch (Exception ex) { }
                                return o;
                            }).ToList();
                        }

    How can I can I pass the model as a string, and get it by it's name? Something like this:

    string model_name = "models.modelos_cab";
    
    List<getModelByName(model_name)> m = new List<getModelByName(model_name)>(); 
    
    var p = typeof(getModelByName(model_name)).GetProperties();
    
    var o = Activator.CreateInstance<getModelByName(model_name)>();

    Is this anyway possible?

    Thank you in advance!

    Tuesday, March 10, 2020 1:44 AM

Answers

  • Hi FireScroll,

    Thank you for posting here.

    You can try the following code to get type by name, but we have to use full name, which means don't forget to add the name of the namespace.

     class Program
        {
            static void Main(string[] args)
            {
                string str = "ConsoleApp2.MyClass";
                Type type =  Type.GetType(str);
                Console.WriteLine(type);
            }
        }
        class MyClass
        {
        }

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, March 10, 2020 3:05 AM
  • Consider using generics. The following should give you a starting point.

    https://stackoverflow.com/questions/8625/generic-type-conversion-from-string


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, March 10, 2020 3:06 AM
    Moderator

All replies

  • Hi FireScroll,

    Thank you for posting here.

    You can try the following code to get type by name, but we have to use full name, which means don't forget to add the name of the namespace.

     class Program
        {
            static void Main(string[] args)
            {
                string str = "ConsoleApp2.MyClass";
                Type type =  Type.GetType(str);
                Console.WriteLine(type);
            }
        }
        class MyClass
        {
        }

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, March 10, 2020 3:05 AM
  • Consider using generics. The following should give you a starting point.

    https://stackoverflow.com/questions/8625/generic-type-conversion-from-string


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, March 10, 2020 3:06 AM
    Moderator
  • Hi,

    You have allready two sugestions for using alternatives, we could all probably get your code to work but it will lead to code that is not very performant and is hard to maintain. 

    It looks like you are trying to solve a problem that others have solved before us. There has always been a difference between data in the database (relational data) and data in our software (objects) You are trying to map these. There are libraries for doing this (Object Relational Mappers (ORM)) in the .Net space the standard is Entity Framework (but it has a learning curve)

    For your use case I would look at the ORM Dapper.  

    For a small Dapper introduction read : https://www.infoworld.com/article/3025784/how-to-use-the-dapper-orm-in-c.html

    For Dapper documentation read : https://dapper-tutorial.net/

    For Entity Framework read : https://docs.microsoft.com/en-us/ef/#pivot=entityfmwk&panel=entityfmwk1


    Hope this helps,

    Here to learn and share. Please tell if an answer was helpful or not at all. This adds value to the answers and enables me to learn more.

    About me

    Tuesday, March 10, 2020 7:50 AM
  • //This is assign the value to list of objects without getting properties.Because property assign dynamically
    var tq = dt.AsEnumerable()
    
    var m = from c in tq select 
    		new modelos_cab{
                         style = c.style,
    			style_customer = c.style_customer,
    			season = c.season,
    			season_description_pt =c.season_description_pt  
    		};
    
    
    
    
    //or
    
    //Retrive the property by the bellow function and then try to assign
    
    public static IEnumerable<DataColumn> GetColumns(DataTable source)
        {
            return source.Columns.AsEnumerable();
        }
    public static String Getcoltype(String dtype)
        {
            var cols = GetColumns(datatableinstants)
    	foreach(var c I cols)
    	(
    	if(c.ColumnName == dtype)
    	{
    	System.Type type = c.GetType();
    		if (type == typeof("System.String"))
     		{
         			return "String"
    		}
    		if (type == typeof("System.Int"))
     		{
         			return "Int"
    		}	
    	}
    	}
        }
    

    Wednesday, March 11, 2020 11:33 AM
  • Hi FireScroll,

    Has your issue been resolved?

    If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 18, 2020 9:43 AM