如何将多个SQL关系映射到c#对象

时间:2019-04-09 10:47:54

标签: c# sql slapper.automapper

我正在开发C#WPF桌面应用程序,需要定期读取/写入SQL数据库(SQL Server)。现在,我想将数据库中的数据映射到C#中的对象。我无法使用实体框架,因此我正在通过Dapper,拍板自动映射器和存储过程进行所有数据访问。

作为示例,我已经为该示例数据库建模

enter image description here

C#对象看起来与此类似。

public class Manager {

   public string Name { get; set; }
   public string Phone { get; set; }
   public List<Facility> Facilities {get; set;}
} 

public class City {

   public string Name { get; set; }
   public string Description{ get; set; }
   public List<Facility> Facilities {get; set;}
} 

public class Facility {

   public string Name { get; set; }
   public string Description{ get; set; }
} 

现在,我用拍板中下划线符号从Dapper中查询表中的数据:

const string sql = @"SELECT 
                                    m.Name,
                                    m.Phone,
                                    m.ManagerId,
                                    f.FacilityId As Facility_FacilityId,
                                    f.WorkerCount As Facility_WorkerCount,
                                    f.SquareFoot As Facility_SquareFoot,
                                    f.Description As Facility_Description,
                                    c.CityId AS Facility_City_CityId,
                                    c.Name AS Facility_City_Name,
                                    c.Description AS Facility_City_Description,

                                    from Manager m  
                                    INNER JOIN  dbo.Facility f  ON  m.ManagerId = f.ManagerId
                                    INNER JOIN  dbo.City c  ON  f.CityId = c.CityId";


            using (System.Data.IDbConnection _connection = new System.Data.SqlClient.SqlConnection("Connstrint"))
            {
               var test = _connection.Query<dynamic>(sql);
                Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(Facility), new List<string> { "FacilityId" });
                Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(Manager), new List<string> { "ManagerId" });
                Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(City), new List<string> { "CityId" });



                var testNetwork = (Slapper.AutoMapper.MapDynamic<Manager>(test) as IEnumerable<Manager>).ToList();
                System.Diagnostics.Debugger.Break();
            }

我知道该映射无法完全正常运行,因为设施无法在对象中前往城市。我应该地图两次吗?从经理那里下来,然后从城市下来一次?还是我应该使用另一种设计模式?

0 个答案:

没有答案