How should I pass data between classes and application layers?

后端 未结 8 1853
太阳男子
太阳男子 2021-01-30 07:16

For example, if I am creating a 3 layer application (data / business / UI) and the data layer is grabbing single or multiple records. Do I convert everything from data layer in

8条回答
  •  萌比男神i
    2021-01-30 07:51

    There are nearly as many "correct" ways to do this as there are programming teams in the world. That said, what I like to do is build a factory for each of my business objects that looks something like this:

    public static class SomeBusinessObjectFactory
    {
       public static SomeBusinessObject FromDataRow(IDataRecord row)
       {
           return new SomeBusinessObject() { Property1 = row["Property1"], Property2 = row["Property2"] ... };
       }
    }
    

    I also have a generic translation method that I use to call these factories:

    public static IEnumerable TranslateQuery(IEnumerable source, Func Factory)
    {
        foreach (IDatarecord item in source)
            yield return Factory(item);
    }
    

    Depending on what your team prefers, the size of the project, etc, these factory objects and translator can live with the business layer or data layer, or even an extra "translation" assembly/layer.

    Then my data layer will have code that looks like this:

    private SqlConnection GetConnection()
    {
        var conn = new SqlConnection( /* connection string loaded from config file */ );
        conn.Open();
        return conn;
    }
    
    private static IEnumerable ExecuteEnumerable(this SqlCommand command)
    {
        using (var rdr = command.ExecuteReader())
        { 
            while (rdr.Read())
            {
                yield return rdr;
            }
        }
    }
    
    public  IEnumerable SomeQuery(int SomeParameter)
    {
        string sql = " .... ";
    
        using (var cn = GetConnection())
        using (var cmd = new SqlCommand(sql, cn))
        {
            cmd.Parameters.Add("@Someparameter", SqlDbType.Int).Value = SomeParameter;
            return cmd.ExecuteEnumerable();
        }
    }
    

    And then I can put it all together like this:

     SomeGridControl.DataSource = TranslateQuery(SomeQuery(5), SomeBusinessObjectFactory.FromDataRow);
    

提交回复
热议问题