使用实体框架或Dapper映射复杂对象

时间:2015-11-23 06:57:55

标签: entity-framework stored-procedures orm dapper asp.net-mvc-5.2

我有一个在ASP MVC 5中开发的网站,我使用的是EF6。 我的模型设计如下:

 public class Person : EntityBase 
{
  public School School {get; set;}
  public string Name {get; set;}
}

public class School : EntityBase 
{
  public List<Course> Courses {get; set;}
  public string Name {get; get;}
  public string Address {get; get;}
}

public class Course : EntityBase 
{
  public List<ItemCourse> ItemCourses {get; set;}
  public Teacher Teacher {get; get;}
}

public class ItemCourse : EntityBase 
{
  public string Name {get; set;}
  public string Summary {get; set;}
}

我有一个包含多个inner join的存储过程,它会从这些表中返回我需要的数据。如何使用entity frameworkdapperADO Net将返回的结果映射到我的实体,我想做一些事情:

personObj.School.Courses[0].ItemCourses[0].Name

实际上我的模型比上面描述的模型更复杂,但想法是一样的。

我手动映射了结果,但映射对象需要30多秒:

using (var con = new SqlConnection(connectionString))
    {
    con.Open();
    var rows = con.Query(
                           "myprocedure",
                           new
                           {
                               param1 = p1,
                               param2 = p2,
                               param3 = p3
                           },
                           commandType: CommandType.StoredProcedure);

    foreach (IDictionary<string, object> row in rows)
    { 
      foreach (var pair in row)
      {
        switch (pair.Key.ToString())
        {
            case "value1" : 
            /*some code here to construct the object, I also check the FK to  
             create a new object or assignt the property to existing obj */
            break;
            .
            .
            . 
            case "value15" :
            //some code here
            break;
        }
      }
    }
}

提前致谢。

0 个答案:

没有答案