DbCommand - ExecuteEntity

A DbCommand extension method that executes the entity operation.

Try it

public static void Main()
{
    Guid guid = Guid.NewGuid();

    var customer = new Customer()
    {
        Id = 2,
        Name = "John",
        Age = 34
    };

    using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
    {
        conn.Open();
        conn.ExecuteNonQuery(@"CREATE TABLE Customers(
 Id   INT              NOT NULL,
 Name VARCHAR (20)     NOT NULL,
 Age  INT              NOT NULL,     
 PRIMARY KEY (Id)
);");

        var dt = new DataTable();
        using (var copy = new SqlBulkCopy(conn))
        {
            foreach (PropertyInfo property in customer.GetType().GetProperties())
            {
                dt.Columns.Add(property.Name, property.PropertyType);

                copy.ColumnMappings.Add(property.Name, property.Name);
            }

            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr);
            foreach (PropertyInfo property in customer.GetType().GetProperties())
            {
                object value = property.GetValue(customer, null);
                dr[property.Name] = value == null ? DBNull.Value : value;
            }

            copy.DestinationTableName = "Customers";

            copy.WriteToServer(dt);
        }

        //C# Extension Method: DbCommand - ExecuteEntity
        var result = conn.ExecuteEntity<Customer>("SELECT TOP 1 * FROM CUSTOMERS");
		
		var list = new List<Customer>() {result};
		
		FiddleHelper.WriteTable(list);
    }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

View Source
using System.Data;
using System.Data.Common;

public static partial class Extensions
{
    /// <summary>
    ///     A DbCommand extension method that executes the entity operation.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <returns>A T.</returns>
    public static T ExecuteEntity<T>(this DbCommand @this) where T : new()
    {
        using (IDataReader reader = @this.ExecuteReader())
        {
            reader.Read();
            return reader.ToEntity<T>();
        }
    }
}