【问题标题】:Get actual model type from dynamic type从动态类型中获取实际模型类型
【发布时间】:2021-09-20 12:09:05
【问题描述】:

我的数据库中有三个表(Student、Course、All)。当我在 Student & Course 表中添加任何数据时,数据也会添加到 All 表中。

所以,我使用 dynamic 类型的数据来传递 Student 和 Course 类型的数据以保存在 All 表中。

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

在 All 服务中,我有一个类似的功能-

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

现在,我需要有关 Student 模型类型的详细信息(表名、找到的总数据等)。

有什么方法可以得到吗?如果我使用动态数据类型,是否可以获得学生或课程模型类型信息?

任何建议或帮助将不胜感激 :) 提前致谢!

【问题讨论】:

    标签: asp.net-core dynamic asp.net-dynamic-data


    【解决方案1】:

    如果要获取模型类型,可以使用model.GetType(),也可以使用model.GetType().Name获取模型类型名称,这里有一个demo:

    型号:

    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; }
    
        }
    

    行动:

    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;
            }
    

    结果:

    【讨论】:

      【解决方案2】:

      这个例子是否展示了你想要做什么?

      // Some dummy classes
      public class Student
      {
          public string Name { get; set; }
      
          public Student(string name)
          {
              Name = name;
          }
      }
      
      public class Course
      {
          public string Title { get; set; }
      
          public Course(string title)
          {
              Title = title;
          }
      }
      
      // put the method somewhere
      private string TypeCasting(dynamic myContent)
      {
          if (myContent is Student littleStudent)
          {
              return littleStudent.Name;
          }
                  
          if (myContent is Course someLovelyCourse)
          {
              return someLovelyCourse.Title;
          }
      
          return string.Empty;
      }
      
      // Example using
      var student = TypeCasting(new Student("fossil"));
      var course = TypeCasting(new Course("type casting"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 2016-12-18
        • 1970-01-01
        • 2013-09-13
        相关资源
        最近更新 更多