C# Extension Method: DbCommand - ExecuteEntities

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002745/dbcommand-executeentities

// @nuget: Z.ExtensionMethods

using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
					
public class Program
{
    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 - ExecuteEntities
            var result = conn.ExecuteEntities<Customer>("SELECT TOP 1 * FROM CUSTOMERS").ToList();
			
			FiddleHelper.WriteTable(result);
        }
    }

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