开发者

Using Microsoft.Practices.EnterpriseLibrary.Data IResultSetMapper<T>

开发者 https://www.devze.com 2023-04-10 01:02 出处:网络
Instead of rolling my own ADO.Net helper classes, I\'ve decided to give the Microsoft.Practices.EnterpriseLibrary a spin. Looking over the documentation, and the sample projects, I\'m really liking wh

Instead of rolling my own ADO.Net helper classes, I've decided to give the Microsoft.Practices.EnterpriseLibrary a spin. Looking over the documentation, and the sample projects, I'm really liking what I'm seeing.

For my project, I will be calling stored procedures for all of my data access. In particular, I will be relying heavily on the ExecuteSprocAccessor<TResult> method.

My question concerns using the IResultSetMapper<T> interface. The docs say classes who implement this interface, must implement the method MapSet(reader:IDataReader):IE开发者_开发百科numerable<T> Unfortunately, I cannot find any examples of how to implement this method.

The following is what I assume is the correct way to use this:

class MyPOCO : IResultSetMapper<MyPOCO>
{
    int    ID   { get; set; }
    string Name { get; set;}

    public IEnumerable<MyPOCO> MapSet(IDataReader reader)
    {
        // HELP ME HERE! PLEASE!
    }
}

Please tell me how to fill in this blank! And if I'm going about this correctly (by having my POCOs implement IResultSetMapper) or if I'm just way off!

Thank you!


Do you really need to use a IResultSetMapper<T>? Are your POCO's simple enough to construct using IRowMapper<T>? If you just have simple objects without hierarchies or nested collections etc. then IRowMapper<T> might be good enough. Although IResultSetMapper<T> does give you the most flexibility.

I wouldn't have the POCO implement IResultSetMapper<T>. I would create a separate mapper class. This eliminates the dependency on Enterprise Library for your POCO class. Also, the POCO class is now independent from the mapping. You can change the mapping or the mapper without impacting the POCO.

public class MyPocoMapper : IResultSetMapper<MyPoco>
{
    public IEnumerable<MyPoco> MapSet ( IDataReader reader )
    {
        using(reader) // Dispose the reader when we're done
        {
            while (reader.Read())
            {
                yield return new MyPoco()
                {
                    MyProperty1 = reader.GetString(
                        reader.GetOrdinal("MyPropertyX")),
                    MyProperty2 = reader.GetString(1)
                };
            }
        }
    }
}


maybe like this

 public IEnumerable<MyPOCO> MapSet(IDataReader reader)
 {
     while(reader.Read())
     yield return new MyPOCO()
                { 
                     ID = reader.GetInt(0),
                     Name = reader.GetString(1) 
                };
 }

if your query looks like whis "select ID,Name from ... "

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号