Loading Entities from DataReader

Posts   
 
    
jakenuts
User
Posts: 10
Joined: 28-Aug-2009
# Posted on: 28-Aug-2009 18:08:30   

Does anyone know the quickest way to load a set of Entities from a DataReader? I have some existing search code which i need to preserve but would like to convert the result to a List<Entity> so I get intellisense in my views.

Thanks!

James

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 28-Aug-2009 19:36:04   

Hi James,

You could use Projections.

How your datareader looks like? LLBLGen version? Adapter or SelfServicin?

David Elizondo | LLBLGen Support Team
jakenuts
User
Posts: 10
Joined: 28-Aug-2009
# Posted on: 28-Aug-2009 19:41:43   

Its a SqlDataReader retreived from another DAL with all the fields from a particular view in my database. I have an entity mapped to that view and just want to load a list of those entities from the reader. I know I could just do it all manually, but I was wondering if there was some shortcut to load a list of entities from a DataReader with the right fields in it.

Thanks!

James

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 29-Aug-2009 09:21:19   

Hi James,

The link I posted above explain that. Here is a little example. 1st method get the DataReader, second method project it (only two fields in this case) to a EntityCollection:

static IDataReader GetCustomerDataReader()      
{ 
SqlConnection conn = null;

string connString = "data source=ACATENANGO;initial catalog=Northwind;integrated security=SSPI;persist security info=False;packet size=4096";
conn = new SqlConnection(connString);
string query = "SELECT * FROM Customers";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}

static void ProjectDataReaderIntoCollection()       
{
EntityCollection customers = new EntityCollection(new CustomersEntityFactory());                        
using (DataAccessAdapter adapter = new DataAccessAdapter())
{
    using (IDataReader reader = GetCustomerDataReader())
    {
        // first resultset: Customers.
        List<IDataValueProjector> valueProjectors = new List<IDataValueProjector>();
        // project value on index 0 in resultset row onto CustomerId
        valueProjectors.Add(new DataValueProjector(CustomersFieldIndex.CustomerId.ToString(), 0, typeof(string)));
        // project value on index 1 in resultset row onto CompanyName
        valueProjectors.Add(new DataValueProjector(CustomersFieldIndex.CompanyName.ToString(), 1, typeof(string)));
        
        // resultset contains more rows, we just project those 2. The rest is trivial.
        DataProjectorToIEntityCollection2 projector = new DataProjectorToIEntityCollection2(customers);
        adapter.FetchProjection(valueProjectors, projector, reader);
        reader.Close();
    }
}
David Elizondo | LLBLGen Support Team