Saturday, July 31, 2010

Translate<T> method in ObjectContext in Entity Framework 4

In Entity Framework 4, ObjectContext has a nice Translate<T> method. This method will materialize the result type. It takes your DbDataReader and materializes the data back into entities, the T can be a primitive type, an entity type, or any custom type you like, That type does not have to be defined in the Entity Framework conceptual model.



If the specified type is of a type that is not defined in the conceptual model or is not a primitive type, the following mapping conventions apply.

The type:
Must not be abstract
Must have a default constructor.

Each property of the type:
Must have a setter.
Must correspond to a primitive type in CSDL.
Must correspond to a column name in the resulting DbDataReader. If the name of the type's property does not match a field of the DbDataReader, the Entity Framework materializes the default value of the property.

I created a helper method as below:
----------------------------------------------------------------
public static class EFStoreHelper
{
    #region CONST
    private const string Const_Provider_Name = "System.Data.SqlClient";
    #endregion
 
    public static DbCommand CreateCommand(DbConnection storeConnection, 
          string cmdText, CommandType cmdType, List<DbParameter> parameters)
    {
        DbCommand command = storeConnection.CreateCommand();
        command.CommandText = cmdText;
        command.CommandType = cmdType;
        if (parameters != null)
        {
            foreach (DbParameter p in parameters)
            {
                command.Parameters.Add(p);
            }
        }
        return command;
    }
 
 
    public static List<T> FillEntities<T>(ObjectContext context, 
                 string cmdText, CommandType cmdType, 
                 List<DbParameter> parameters, 
                 LeaveConnectionState leaveConnectionState)
    {
        DbConnection storeConnection = context.StoreConnection;
 
        DbDataReader dr = null;
        try
        {
            DbCommand cmd = CreateCommand(storeConnection, cmdText, cmdType, parameters);
            dr = ExecuteReader(cmd, leaveConnectionState);
            System.Data.Objects.ObjectResult<T> result = context.Translate<T>(dr);
            return result.ToList<T>();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (leaveConnectionState == LeaveConnectionState.Closed)
            {
                storeConnection.Close();
            }
            if (dr != null)
            {
                dr.Close();
                dr.Dispose();
            }
        }
    }
}

Cheers!

1 comments:

Yasser Shaikh said...

whats LeaveConnectionState ?

Post a Comment