asp.net-coredynamicasp.net-dynamic-data

Get actual model type from dynamic type


I have three tables in my database (Student, Course, All). When I add any data in Student & Course table, the data also gets added in All table.

So, I'm using dynamic type data to pass Student & Course type data to get saved in All table.

public IActionResult Add(Student model) 
{   ... 
 bool studentData = _studentService.Add(model); //saving in Student table 
 bool allData= _allService.AddAll(model); // passing 'Student' type data 
   ... 
}

In the All service, I've a function like-

public bool AddAll(dynamic model) // 'Student' type data passed & received as dynamic 
{...}

Now, I need the details about Student model type (table name, total data found etc.).

Is there any way to get it? And is it possible to get the Student or Course model type info if I use dynamic data type?

Any suggestion or help will be much appreciated :) Thanks in advance!


Solution

  • If you want to get model type,you can use model.GetType(),and you can use model.GetType().Name to get model type Name,here is a demo:

    Model:

    public class Student
        {
            public int StudentId { get; set; }
            public string StudentName { get; set; }
    
        }
    
        public class Course
        {
            public int CourseId { get; set; }
            public string CourseName { get; set; }
    
        }
    

    Action:

    public void Add(Student model)
            {
                //Student s = new Student { StudentId=1, StudentName="s1" };
                Course c = new Course { CourseId=1,CourseName="c1" };
                bool allData = AddAll(c);
            }
            public bool AddAll(dynamic model)
            {
                var type = model.GetType();
                var typeName = type.Name;
                return true;
            }
    

    result: enter image description here