代码之家  ›  专栏  ›  技术社区  ›  Diego Alves

有没有一种简单的方法可以在不使用orm的情况下将一对多关系分配给c中的对象?[关闭]

  •  -2
  • Diego Alves  · 技术社区  · 6 年前

    我特别不喜欢orms,但我正陷入一种无法想到足够简单的逻辑来解决问题的境地。

    例如,如果一个具有与子类别“一对多关系”的类别表,则查询可能会生成如下内容:

    category     subcategory
    eletronics    keyboards
    eletronics    mouses
    fashion       t-shirt
    fashion        hat
    

    我想不出一个简单的逻辑来使用数据读取器将其“映射”到如下对象:

    public class Category
    {
      public string Category {get ; set;}
      public List<Subcategory> Subcategory {get; set;} new Subcategory();
    }
    

    我在一个应用程序中用雄辩的语言完成了同样的任务,这是微不足道的。

    我正在考虑安装一个orm包并使用对象关系映射器来执行此任务,并在应用程序的其余部分使用原始sql命令。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Svek    6 年前

    有很多的教程,但给你一个例子,可以找到在 Microsoft Docs

    public class Category
    {
        public int Id {get; set;}
        public string Name {get; set;}
        public List<SubCategory> SubCategory {get; set;}
    }
    
    public class SubCategory
    {
        public int Id {get; set;}
        public string Parent {get; set;}
        public string Name {get; set;}
    }
    

    然后你会有一个方法像…

    static List<Category> RetrieveCategories(SqlConnection connection)
    {
        using (connection)
        {
            SqlCommand command = new SqlCommand(
              "SELECT Id, Name FROM dbo.Categories;" +
              "SELECT Id, Parent, Name FROM dbo.SubCategories",
              connection);
            connection.Open();
    
            SqlDataReader reader = command.ExecuteReader();
    
            List<Category> result = new List<Category>();
    
            // grab the categories
            while (reader.Read())
            {
                var category = new Category()
                {
                    Id = reader.GetInt32(0),
                    Name = reader.GetString(1)
                    SubCategory = new List<SubCategory>();
                };
    
                result.Add(category);
            }
    
            sqlReader.NextResult();
    
            // grab the sub categories
            while (reader.Read())
            {
                var subCategory = new SubCategory()
                {
                    Id = reader.GetInt32(0),
                    Parent = reader.GetString(1),
                    Name = reader.GetString(2)
                };
    
                // add the sub categories to the results
                results.Where(_ => _.Name == subcategory.Parent)
                       .FirstOrDefault()
                       .SubCategory.Add(subcategory);
    
            }
        }
    }
    

    请注意,这并不是真正高度优化的代码,但它只是为了说明确实可以使用 DataReader .

        2
  •  1
  •   Diego Alves    6 年前

    我能够开发一个简单的代码,现在我不会安装一个ORM包。

    如果a有这样的结果集:

     id(category id)  category_name subcategory_name
     1                 eletronic      keyboard
     1                 eletronic        mouse
     2                  fashion         t-shirt
     2                   fashion         hat
    

    结果集必须按ID排序, 我可以做这样的事情:

     List<Category> categories = new List<Category>();
    
     //I will use this variable to hold the category id of the row that the datareader is reading
      int categoryId= 0;  
    
      Category category = null;
    
        while (dr.Read())
            {    
                 //if the current category id is different than the variable categoryId I will instantiante a new Category,
                // otherwise I will add the a new subcategory to the existing category object
    
                if(categoryId != dr.GetInt32(dr.GetOrdinal("id")))
                    { 
                        category = new Category();
                        category.CategoryName =   dr.GetString(dr.GetOrdinal("category_name"));
    
                        category.Subcategory.Add(new Subcategory { SubcategoryName = dr.GetString(dr.GetOrdinal("subcategory_name")) });
    
                    }
                    else
                    {
                        category.Subcategory.Add(new Subcategory { SubcategoryName = dr.GetString(dr.GetOrdinal("subcategory_name")) });
    
                    }
    
                    if (categoryId != dr.GetInt32(dr.GetOrdinal("id")) && category !=null)
                    {
                        categorias.Add(category);
                    }
    
                  categoryId =  dr.GetInt32(dr.GetOrdinal("id"));
                }
    
    
                conn.Close();
    
                return categories;
    

    基本上,如果id更改,我会迭代结果集,否则我会实例化一个新类别,否则我会向当前类别对象添加一个新的子类别。