Generate class from a LINQ projection

using System;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom;

public static class QueryExtensions
public static string GetClassDefinition<T>(this IQueryable<T> query, string className)
var type = typeof(T);
var sb = new StringBuilder();
sb.AppendLine(string.Format("public class {0}", className));
using (var provider = new CSharpCodeProvider())
foreach ( var prop in type.GetProperties())
var typeRef = new CodeTypeReference(prop.PropertyType);
var propertyTypeName = provider.GetTypeOutput(typeRef);
if ( !propertyTypeName.StartsWith("<>"))
propertyTypeName = propertyTypeName.Replace("System.Nullable<", String.Empty)
.Replace("System.", String.Empty);
sb.AppendLine(string.Format("\tpublic {0} {1} {{get; set;}}", propertyTypeName, prop.Name));
return sb.ToString();

The reason of this snippet is because I was working to the following query which projects kind many properties and I want to reuse the results, so I needed to write a concrete class. Usually I build and test the queries with LINQPad so here follows a capture of my original query.

Creating a class with a bunch of properties is not the happiest moment, so I decided to generate it. The class looks like:

public class OrderItemDetails
public int order_item_id {get; set;}
public int order_id {get; set;}
public string session_id {get; set;}
public string root_plu {get; set;}
public string full_plu {get; set;}
public int? product_id {get; set;}
public int stock_id {get; set;}
public int quantity {get; set;}
public decimal item_value {get; set;}
public decimal unit_price {get; set;}
public decimal adjusted_price {get; set;}
public string product_image {get; set;}
public string product_name {get; set;}
public string product_size {get; set;}
public string product_colour {get; set;}
public string preorder_status {get; set;}
public int item_status_id {get; set;}
public string order_item_status_title {get; set;}
public int? Delivery_id {get; set;}
public int? Delivery_band_id {get; set;}
public int shipping_carrier_id {get; set;}
public string carrier_name {get; set;}
public string url {get; set;}
public string tracking_code {get; set;}
public bool printed_for_tracking {get; set;}
public bool printed_for_dispatch {get; set;}
public string credited_reason {get; set;}
public decimal? credited_amount {get; set;}
public bool refunded {get; set;}
public string refunded_reason {get; set;}
public bool exchanged {get; set;}
public string exchanged_reason {get; set;}
public DateTime dispatched_date {get; set;}
public bool? change_quantity {get; set;}
public bool awaiting_stock {get; set;}
public int? parent_id {get; set;}
public bool suburban {get; set;}
public DateTime created_on {get; set;}
public DateTime updated_on {get; set;}
public bool? deleted {get; set;}


Popular posts from this blog


Table Per Hierarchy Inheritance with Column Discriminator and Associations used in Derived Entity Types