Commit 5d9e188b authored by Sam Saffron's avatar Sam Saffron

initial commit

parents
/*.suo
bin/*
obj/*
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;
[assembly: EdmSchemaAttribute()]
namespace SqlMapper.EntityFramework
{
#region Contexts
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public partial class tempdbEntities1 : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new tempdbEntities1 object using the connection string found in the 'tempdbEntities1' section of the application configuration file.
/// </summary>
public tempdbEntities1() : base("name=tempdbEntities1", "tempdbEntities1")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new tempdbEntities1 object.
/// </summary>
public tempdbEntities1(string connectionString) : base(connectionString, "tempdbEntities1")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new tempdbEntities1 object.
/// </summary>
public tempdbEntities1(EntityConnection connection) : base(connection, "tempdbEntities1")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
#endregion
#region Partial Methods
partial void OnContextCreated();
#endregion
#region ObjectSet Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Post> Posts
{
get
{
if ((_Posts == null))
{
_Posts = base.CreateObjectSet<Post>("Posts");
}
return _Posts;
}
}
private ObjectSet<Post> _Posts;
#endregion
#region AddTo Methods
/// <summary>
/// Deprecated Method for adding a new object to the Posts EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
/// </summary>
public void AddToPosts(Post post)
{
base.AddObject("Posts", post);
}
#endregion
}
#endregion
#region Entities
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="tempdbModel", Name="Post")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Post : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Post object.
/// </summary>
/// <param name="id">Initial value of the Id property.</param>
/// <param name="text">Initial value of the Text property.</param>
/// <param name="creationDate">Initial value of the CreationDate property.</param>
/// <param name="lastChangeDate">Initial value of the LastChangeDate property.</param>
public static Post CreatePost(global::System.Int32 id, global::System.String text, global::System.DateTime creationDate, global::System.DateTime lastChangeDate)
{
Post post = new Post();
post.Id = id;
post.Text = text;
post.CreationDate = creationDate;
post.LastChangeDate = lastChangeDate;
return post;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Id
{
get
{
return _Id;
}
set
{
if (_Id != value)
{
OnIdChanging(value);
ReportPropertyChanging("Id");
_Id = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Id");
OnIdChanged();
}
}
}
private global::System.Int32 _Id;
partial void OnIdChanging(global::System.Int32 value);
partial void OnIdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Text
{
get
{
return _Text;
}
set
{
OnTextChanging(value);
ReportPropertyChanging("Text");
_Text = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Text");
OnTextChanged();
}
}
private global::System.String _Text;
partial void OnTextChanging(global::System.String value);
partial void OnTextChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.DateTime CreationDate
{
get
{
return _CreationDate;
}
set
{
OnCreationDateChanging(value);
ReportPropertyChanging("CreationDate");
_CreationDate = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CreationDate");
OnCreationDateChanged();
}
}
private global::System.DateTime _CreationDate;
partial void OnCreationDateChanging(global::System.DateTime value);
partial void OnCreationDateChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.DateTime LastChangeDate
{
get
{
return _LastChangeDate;
}
set
{
OnLastChangeDateChanging(value);
ReportPropertyChanging("LastChangeDate");
_LastChangeDate = StructuralObject.SetValidValue(value);
ReportPropertyChanged("LastChangeDate");
OnLastChangeDateChanged();
}
}
private global::System.DateTime _LastChangeDate;
partial void OnLastChangeDateChanging(global::System.DateTime value);
partial void OnLastChangeDateChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter1
{
get
{
return _Counter1;
}
set
{
OnCounter1Changing(value);
ReportPropertyChanging("Counter1");
_Counter1 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter1");
OnCounter1Changed();
}
}
private Nullable<global::System.Int32> _Counter1;
partial void OnCounter1Changing(Nullable<global::System.Int32> value);
partial void OnCounter1Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter2
{
get
{
return _Counter2;
}
set
{
OnCounter2Changing(value);
ReportPropertyChanging("Counter2");
_Counter2 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter2");
OnCounter2Changed();
}
}
private Nullable<global::System.Int32> _Counter2;
partial void OnCounter2Changing(Nullable<global::System.Int32> value);
partial void OnCounter2Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter3
{
get
{
return _Counter3;
}
set
{
OnCounter3Changing(value);
ReportPropertyChanging("Counter3");
_Counter3 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter3");
OnCounter3Changed();
}
}
private Nullable<global::System.Int32> _Counter3;
partial void OnCounter3Changing(Nullable<global::System.Int32> value);
partial void OnCounter3Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter4
{
get
{
return _Counter4;
}
set
{
OnCounter4Changing(value);
ReportPropertyChanging("Counter4");
_Counter4 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter4");
OnCounter4Changed();
}
}
private Nullable<global::System.Int32> _Counter4;
partial void OnCounter4Changing(Nullable<global::System.Int32> value);
partial void OnCounter4Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter5
{
get
{
return _Counter5;
}
set
{
OnCounter5Changing(value);
ReportPropertyChanging("Counter5");
_Counter5 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter5");
OnCounter5Changed();
}
}
private Nullable<global::System.Int32> _Counter5;
partial void OnCounter5Changing(Nullable<global::System.Int32> value);
partial void OnCounter5Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter6
{
get
{
return _Counter6;
}
set
{
OnCounter6Changing(value);
ReportPropertyChanging("Counter6");
_Counter6 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter6");
OnCounter6Changed();
}
}
private Nullable<global::System.Int32> _Counter6;
partial void OnCounter6Changing(Nullable<global::System.Int32> value);
partial void OnCounter6Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter7
{
get
{
return _Counter7;
}
set
{
OnCounter7Changing(value);
ReportPropertyChanging("Counter7");
_Counter7 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter7");
OnCounter7Changed();
}
}
private Nullable<global::System.Int32> _Counter7;
partial void OnCounter7Changing(Nullable<global::System.Int32> value);
partial void OnCounter7Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter8
{
get
{
return _Counter8;
}
set
{
OnCounter8Changing(value);
ReportPropertyChanging("Counter8");
_Counter8 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter8");
OnCounter8Changed();
}
}
private Nullable<global::System.Int32> _Counter8;
partial void OnCounter8Changing(Nullable<global::System.Int32> value);
partial void OnCounter8Changed();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Counter9
{
get
{
return _Counter9;
}
set
{
OnCounter9Changing(value);
ReportPropertyChanging("Counter9");
_Counter9 = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Counter9");
OnCounter9Changed();
}
}
private Nullable<global::System.Int32> _Counter9;
partial void OnCounter9Changing(Nullable<global::System.Int32> value);
partial void OnCounter9Changed();
#endregion
}
#endregion
}
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="tempdbModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="tempdbModelStoreContainer">
<EntitySet Name="Posts" EntityType="tempdbModel.Store.Posts" store:Type="Tables" Schema="dbo" />
</EntityContainer>
<EntityType Name="Posts">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="Text" Type="varchar(max)" Nullable="false" />
<Property Name="CreationDate" Type="datetime" Nullable="false" />
<Property Name="LastChangeDate" Type="datetime" Nullable="false" />
<Property Name="Counter1" Type="int" />
<Property Name="Counter2" Type="int" />
<Property Name="Counter3" Type="int" />
<Property Name="Counter4" Type="int" />
<Property Name="Counter5" Type="int" />
<Property Name="Counter6" Type="int" />
<Property Name="Counter7" Type="int" />
<Property Name="Counter8" Type="int" />
<Property Name="Counter9" Type="int" />
</EntityType>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="tempdbModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="tempdbEntities1" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Posts" EntityType="tempdbModel.Post" />
</EntityContainer>
<EntityType Name="Post">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="Text" Type="String" Nullable="false" MaxLength="Max" Unicode="false" FixedLength="false" />
<Property Name="CreationDate" Type="DateTime" Nullable="false" />
<Property Name="LastChangeDate" Type="DateTime" Nullable="false" />
<Property Name="Counter1" Type="Int32" />
<Property Name="Counter2" Type="Int32" />
<Property Name="Counter3" Type="Int32" />
<Property Name="Counter4" Type="Int32" />
<Property Name="Counter5" Type="Int32" />
<Property Name="Counter6" Type="Int32" />
<Property Name="Counter7" Type="Int32" />
<Property Name="Counter8" Type="Int32" />
<Property Name="Counter9" Type="Int32" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="tempdbModelStoreContainer" CdmEntityContainer="tempdbEntities1">
<EntitySetMapping Name="Posts"><EntityTypeMapping TypeName="tempdbModel.Post"><MappingFragment StoreEntitySet="Posts">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="Text" ColumnName="Text" />
<ScalarProperty Name="CreationDate" ColumnName="CreationDate" />
<ScalarProperty Name="LastChangeDate" ColumnName="LastChangeDate" />
<ScalarProperty Name="Counter1" ColumnName="Counter1" />
<ScalarProperty Name="Counter2" ColumnName="Counter2" />
<ScalarProperty Name="Counter3" ColumnName="Counter3" />
<ScalarProperty Name="Counter4" ColumnName="Counter4" />
<ScalarProperty Name="Counter5" ColumnName="Counter5" />
<ScalarProperty Name="Counter6" ColumnName="Counter6" />
<ScalarProperty Name="Counter7" ColumnName="Counter7" />
<ScalarProperty Name="Counter8" ColumnName="Counter8" />
<ScalarProperty Name="Counter9" ColumnName="Counter9" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</Connection>
<Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="True" />
<DesignerProperty Name="IncludeForeignKeysInModel" Value="True" />
</DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -->
<Diagrams>
<Diagram Name="Model">
<EntityTypeShape EntityType="tempdbModel.Post" Width="1.5" PointX="0.75" PointY="1" Height="3.7109993489583313" IsExpanded="true" />
</Diagram>
</Diagrams>
</Designer>
</edmx:Edmx>
\ No newline at end of file
Copyright (c) 2010 Stack Overflow Internet Services, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<?xml version="1.0" encoding="utf-8"?><Database Name="tempdb" Class="DataClassesDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
<Connection Mode="AppSettings" ConnectionString="Data Source=.;Initial Catalog=tempdb;Integrated Security=True" SettingsObjectName="SqlMapper.Properties.Settings" SettingsPropertyName="tempdbConnectionString" Provider="System.Data.SqlClient" />
<Table Name="dbo.Posts" Member="Posts">
<Type Name="Post">
<Column Name="Id" Type="System.Int32" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />
<Column Name="Text" Type="System.String" DbType="VarChar(MAX) NOT NULL" CanBeNull="false" />
<Column Name="CreationDate" Type="System.DateTime" DbType="DateTime NOT NULL" CanBeNull="false" />
<Column Name="LastChangeDate" Type="System.DateTime" DbType="DateTime NOT NULL" CanBeNull="false" />
<Column Name="Counter1" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter2" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter3" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter4" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter5" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter6" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter7" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter8" Type="System.Int32" DbType="Int" CanBeNull="true" />
<Column Name="Counter9" Type="System.Int32" DbType="Int" CanBeNull="true" />
</Type>
</Table>
</Database>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<ordesignerObjectsDiagram dslVersion="1.0.0.0" absoluteBounds="0, 0, 11, 8.5" name="DataClasses">
<DataContextMoniker Name="/DataClassesDataContext" />
<nestedChildShapes>
<classShape Id="7c7fe5bb-e9b7-4aa5-b2d5-1958b0d557f7" absoluteBounds="0.75, 1.125, 2, 3.3093082682291666">
<DataClassMoniker Name="/DataClassesDataContext/Post" />
<nestedChildShapes>
<elementListCompartment Id="2d5a0585-b7b4-4679-a1f6-40b15c5b284e" absoluteBounds="0.765, 1.585, 1.9700000000000002, 2.7493082682291665" name="DataPropertiesCompartment" titleTextColor="Black" itemTextColor="Black" />
</nestedChildShapes>
</classShape>
</nestedChildShapes>
</ordesignerObjectsDiagram>
\ No newline at end of file
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SqlMapper.Linq2Sql
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="tempdb")]
public partial class DataClassesDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
partial void InsertPost(Post instance);
partial void UpdatePost(Post instance);
partial void DeletePost(Post instance);
#endregion
public DataClassesDataContext() :
base(global::SqlMapper.Properties.Settings.Default.tempdbConnectionString, mappingSource)
{
OnCreated();
}
public DataClassesDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClassesDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClassesDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClassesDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<Post> Posts
{
get
{
return this.GetTable<Post>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Posts")]
public partial class Post : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private string _Text;
private System.DateTime _CreationDate;
private System.DateTime _LastChangeDate;
private System.Nullable<int> _Counter1;
private System.Nullable<int> _Counter2;
private System.Nullable<int> _Counter3;
private System.Nullable<int> _Counter4;
private System.Nullable<int> _Counter5;
private System.Nullable<int> _Counter6;
private System.Nullable<int> _Counter7;
private System.Nullable<int> _Counter8;
private System.Nullable<int> _Counter9;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnIdChanging(int value);
partial void OnIdChanged();
partial void OnTextChanging(string value);
partial void OnTextChanged();
partial void OnCreationDateChanging(System.DateTime value);
partial void OnCreationDateChanged();
partial void OnLastChangeDateChanging(System.DateTime value);
partial void OnLastChangeDateChanged();
partial void OnCounter1Changing(System.Nullable<int> value);
partial void OnCounter1Changed();
partial void OnCounter2Changing(System.Nullable<int> value);
partial void OnCounter2Changed();
partial void OnCounter3Changing(System.Nullable<int> value);
partial void OnCounter3Changed();
partial void OnCounter4Changing(System.Nullable<int> value);
partial void OnCounter4Changed();
partial void OnCounter5Changing(System.Nullable<int> value);
partial void OnCounter5Changed();
partial void OnCounter6Changing(System.Nullable<int> value);
partial void OnCounter6Changed();
partial void OnCounter7Changing(System.Nullable<int> value);
partial void OnCounter7Changed();
partial void OnCounter8Changing(System.Nullable<int> value);
partial void OnCounter8Changed();
partial void OnCounter9Changing(System.Nullable<int> value);
partial void OnCounter9Changed();
#endregion
public Post()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this.OnIdChanging(value);
this.SendPropertyChanging();
this._Id = value;
this.SendPropertyChanged("Id");
this.OnIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Text", DbType="VarChar(MAX) NOT NULL", CanBeNull=false)]
public string Text
{
get
{
return this._Text;
}
set
{
if ((this._Text != value))
{
this.OnTextChanging(value);
this.SendPropertyChanging();
this._Text = value;
this.SendPropertyChanged("Text");
this.OnTextChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CreationDate", DbType="DateTime NOT NULL")]
public System.DateTime CreationDate
{
get
{
return this._CreationDate;
}
set
{
if ((this._CreationDate != value))
{
this.OnCreationDateChanging(value);
this.SendPropertyChanging();
this._CreationDate = value;
this.SendPropertyChanged("CreationDate");
this.OnCreationDateChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastChangeDate", DbType="DateTime NOT NULL")]
public System.DateTime LastChangeDate
{
get
{
return this._LastChangeDate;
}
set
{
if ((this._LastChangeDate != value))
{
this.OnLastChangeDateChanging(value);
this.SendPropertyChanging();
this._LastChangeDate = value;
this.SendPropertyChanged("LastChangeDate");
this.OnLastChangeDateChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter1", DbType="Int")]
public System.Nullable<int> Counter1
{
get
{
return this._Counter1;
}
set
{
if ((this._Counter1 != value))
{
this.OnCounter1Changing(value);
this.SendPropertyChanging();
this._Counter1 = value;
this.SendPropertyChanged("Counter1");
this.OnCounter1Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter2", DbType="Int")]
public System.Nullable<int> Counter2
{
get
{
return this._Counter2;
}
set
{
if ((this._Counter2 != value))
{
this.OnCounter2Changing(value);
this.SendPropertyChanging();
this._Counter2 = value;
this.SendPropertyChanged("Counter2");
this.OnCounter2Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter3", DbType="Int")]
public System.Nullable<int> Counter3
{
get
{
return this._Counter3;
}
set
{
if ((this._Counter3 != value))
{
this.OnCounter3Changing(value);
this.SendPropertyChanging();
this._Counter3 = value;
this.SendPropertyChanged("Counter3");
this.OnCounter3Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter4", DbType="Int")]
public System.Nullable<int> Counter4
{
get
{
return this._Counter4;
}
set
{
if ((this._Counter4 != value))
{
this.OnCounter4Changing(value);
this.SendPropertyChanging();
this._Counter4 = value;
this.SendPropertyChanged("Counter4");
this.OnCounter4Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter5", DbType="Int")]
public System.Nullable<int> Counter5
{
get
{
return this._Counter5;
}
set
{
if ((this._Counter5 != value))
{
this.OnCounter5Changing(value);
this.SendPropertyChanging();
this._Counter5 = value;
this.SendPropertyChanged("Counter5");
this.OnCounter5Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter6", DbType="Int")]
public System.Nullable<int> Counter6
{
get
{
return this._Counter6;
}
set
{
if ((this._Counter6 != value))
{
this.OnCounter6Changing(value);
this.SendPropertyChanging();
this._Counter6 = value;
this.SendPropertyChanged("Counter6");
this.OnCounter6Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter7", DbType="Int")]
public System.Nullable<int> Counter7
{
get
{
return this._Counter7;
}
set
{
if ((this._Counter7 != value))
{
this.OnCounter7Changing(value);
this.SendPropertyChanging();
this._Counter7 = value;
this.SendPropertyChanged("Counter7");
this.OnCounter7Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter8", DbType="Int")]
public System.Nullable<int> Counter8
{
get
{
return this._Counter8;
}
set
{
if ((this._Counter8 != value))
{
this.OnCounter8Changing(value);
this.SendPropertyChanging();
this._Counter8 = value;
this.SendPropertyChanged("Counter8");
this.OnCounter8Changed();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Counter9", DbType="Int")]
public System.Nullable<int> Counter9
{
get
{
return this._Counter9;
}
set
{
if ((this._Counter9 != value))
{
this.OnCounter9Changing(value);
this.SendPropertyChanging();
this._Counter9 = value;
this.SendPropertyChanged("Counter9");
this.OnCounter9Changed();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
#pragma warning restore 1591
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlMapper.Linq2Sql
{
public partial class Post
{
/*
public int Bloat { get; set; }
public int Bloat1 { get; set; }
public int Bloat2 { get; set; }
public int Bloat3 { get; set; }
public int Bloat4 { get; set; }
public int Bloat5 { get; set; }
public int Bloat6 { get; set; }
public int Bloat7 { get; set; }
public int Bloat8 { get; set; }
public int Bloat10 { get; set; }
public int Bloat11 { get; set; }
public int Bloat12 { get; set; }
public int Bloat13 { get; set; }
public int Bloat14 { get; set; }
public int Bloat15 { get; set; }
public int Bloat16 { get; set; }
public int Bloat17 { get; set; }
public int Bloat18 { get; set; }
*/
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using SqlMapper.Linq2Sql;
using System.Data.Linq;
using System.Diagnostics;
namespace SqlMapper
{
class PerformanceTests
{
class Test
{
public static Test Create(Action<int> iteration, string name)
{
return new Test {Iteration = iteration, Name = name };
}
public Action<int> Iteration { get; set; }
public string Name { get; set; }
public Stopwatch Watch { get; set; }
}
class Tests : List<Test>
{
public void Add(Action<int> iteration, string name)
{
Add(Test.Create(iteration, name));
}
public void Run(int iterations)
{
// warmup
foreach (var test in this)
{
test.Iteration(iterations + 1);
test.Watch = new Stopwatch();
test.Watch.Reset();
}
var rand = new Random();
for (int i = 1; i <= iterations; i++)
{
foreach (var test in this.OrderBy(ignore => rand.Next()))
{
test.Watch.Start();
test.Iteration(i);
test.Watch.Stop();
}
}
foreach (var test in this.OrderBy(t => t.Watch.ElapsedMilliseconds))
{
Console.WriteLine(test.Name + " took " + test.Watch.ElapsedMilliseconds + "ms");
}
}
}
static DataClassesDataContext GetL2SContext()
{
return new DataClassesDataContext(Program.GetOpenConnection());
}
public void Run(int iterations)
{
var tests = new Tests();
var l2scontext1 = GetL2SContext();
tests.Add(id => l2scontext1.Posts.First(p => p.Id == id), "Linq 2 SQL");
var l2scontext2 = GetL2SContext();
var compiledGetPost = CompiledQuery.Compile((Linq2Sql.DataClassesDataContext ctx, int id) => ctx.Posts.First(p => p.Id == id));
tests.Add(id => compiledGetPost(l2scontext2,id), "Linq 2 SQL Compiled");
var l2scontext3 = GetL2SContext();
tests.Add(id => l2scontext3.ExecuteQuery<Post>("select * from Posts where Id = {0}", id).ToList(), "Linq 2 SQL ExecuteQuery");
var entityContext = new EntityFramework.tempdbEntities1();
entityContext.Connection.Open();
tests.Add(id => entityContext.Posts.First(p => p.Id == id), "Entity framework");
var entityContext2 = new EntityFramework.tempdbEntities1();
entityContext2.Connection.Open();
tests.Add(id => entityContext.ExecuteStoreQuery<Post>("select * from Posts where Id = {0}", id).ToList(), "Entity framework ExecuteStoreQuery");
var mapperConnection = Program.GetOpenConnection();
tests.Add(id => mapperConnection.ExecuteMapperQuery<Post>("select * from Posts where Id = @Id", new { Id = id }).ToList(), "Mapper Query");
// HAND CODED
var connection = Program.GetOpenConnection();
var postCommand = new SqlCommand();
postCommand.Connection = connection;
postCommand.CommandText = @"select Id, [Text], [CreationDate], LastChangeDate,
Counter1,Counter2,Counter3,Counter4,Counter5,Counter6,Counter7,Counter8,Counter9 from Posts where Id = @Id";
var idParam = postCommand.Parameters.Add("@Id", System.Data.SqlDbType.Int);
tests.Add(id =>
{
idParam.Value = id;
using (var reader = postCommand.ExecuteReader())
{
reader.Read();
var post = new Post();
post.Id = reader.GetInt32(0);
post.Text = reader.GetString(1);
post.CreationDate = reader.GetDateTime(2);
post.LastChangeDate = reader.GetDateTime(3);
post.Counter1 = reader.IsDBNull(4) ? (int?)null : reader.GetInt32(4);
post.Counter2 = reader.IsDBNull(5) ? (int?)null : reader.GetInt32(5);
post.Counter3 = reader.IsDBNull(6) ? (int?)null : reader.GetInt32(6);
post.Counter4 = reader.IsDBNull(7) ? (int?)null : reader.GetInt32(7);
post.Counter5 = reader.IsDBNull(8) ? (int?)null : reader.GetInt32(8);
post.Counter6 = reader.IsDBNull(9) ? (int?)null : reader.GetInt32(9);
post.Counter7 = reader.IsDBNull(10) ? (int?)null : reader.GetInt32(10);
post.Counter8 = reader.IsDBNull(11) ? (int?)null : reader.GetInt32(11);
post.Counter9 = reader.IsDBNull(12) ? (int?)null : reader.GetInt32(12);
}
}, "hand coded");
tests.Run(iterations);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data.Metadata.Edm;
using System.Reflection;
using System.Data.EntityClient;
using System.Data.Linq;
namespace SqlMapper
{
class Post
{
public int Id { get; set; }
public string Text { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastChangeDate { get; set; }
public int? Counter1 { get; set; }
public int? Counter2 { get; set; }
public int? Counter3 { get; set; }
public int? Counter4 { get; set; }
public int? Counter5 { get; set; }
public int? Counter6 { get; set; }
public int? Counter7 { get; set; }
public int? Counter8 { get; set; }
public int? Counter9 { get; set; }
}
class Program
{
public static SqlConnection GetOpenConnection()
{
var connection = new SqlConnection("Data Source=.;Initial Catalog=tempdb;Integrated Security=True");
connection.Open();
return connection;
}
static void RunPerformanceTests()
{
var test = new PerformanceTests();
Console.WriteLine("Running 500 itrations that load up a post entity");
test.Run(500);
}
static void Main(string[] args)
{
#if DEBUG
RunTests();
#else
EnsureDBSetup();
RunPerformanceTests();
#endif
Console.ReadKey();
}
private static void EnsureDBSetup()
{
using (var cnn = GetOpenConnection())
{
var cmd = cnn.CreateCommand();
cmd.CommandText = @"
if (OBJECT_ID('Posts') is null)
begin
create table Posts
(
Id int identity primary key,
[Text] varchar(max) not null,
CreationDate datetime not null,
LastChangeDate datetime not null,
Counter1 int,
Counter2 int,
Counter3 int,
Counter4 int,
Counter5 int,
Counter6 int,
Counter7 int,
Counter8 int,
Counter9 int
)
set nocount on
declare @i int
declare @c int
declare @id int
set @i = 0
while @i < 5000
begin
insert Posts ([Text],CreationDate, LastChangeDate) values (replicate('x', 2000), GETDATE(), GETDATE())
set @id = @@IDENTITY
set @i = @i + 1
end
end
";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
}
}
private static void RunTests()
{
var tester = new Tests();
foreach (var method in typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
}
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Smackdown")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Smackdown")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("77246f63-77a4-4d9f-a4d6-62282d67c8be")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SqlMapper.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=.;Initial Catalog=tempdb;Integrated Security=True")]
public string tempdbConnectionString {
get {
return ((string)(this["tempdbConnectionString"]));
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Smackdown.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="tempdbConnectionString" Type="(Connection string)" Scope="Application">
<DesignTimeValue Profile="(Default)">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
&lt;ConnectionString&gt;Data Source=.;Initial Catalog=tempdb;Integrated Security=True&lt;/ConnectionString&gt;
&lt;ProviderName&gt;System.Data.SqlClient&lt;/ProviderName&gt;
&lt;/SerializableConnectionString&gt;</DesignTimeValue>
<Value Profile="(Default)">Data Source=.;Initial Catalog=tempdb;Integrated Security=True</Value>
</Setting>
</Settings>
</SettingsFile>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Reflection.Emit;
using System.Collections.Concurrent;
using System.Data;
using System.Reflection;
using Microsoft.SqlServer.Server;
using System.Security.Cryptography;
namespace SqlMapper
{
public static class SqlMapper
{
static SqlMapper()
{
typeMap = new Dictionary<Type, SqlDbType>();
typeMap[typeof(int)] = SqlDbType.Int;
typeMap[typeof(int?)] = SqlDbType.Int;
typeMap[typeof(string)] = SqlDbType.NVarChar;
typeMap[typeof(Guid)] = SqlDbType.UniqueIdentifier;
typeMap[typeof(Guid?)] = SqlDbType.UniqueIdentifier;
typeMap[typeof(int[])] = SqlDbType.Structured;
typeMap[typeof(List<int>)] = SqlDbType.Structured;
}
class ParamInfo
{
private ParamInfo()
{
}
public static ParamInfo Create(string name, SqlDbType type, object val)
{
return new ParamInfo { Name = name, Type = type, Val = val };
}
public SqlDbType Type { get; private set; }
public string Name { get; private set; }
public object Val { get; private set; }
}
private class Identity : IEquatable<Identity>
{
public Type Type { get { return type; } }
public string Sql { get { return sql; } }
internal Identity(string sql, Type type)
{
this.sql = sql;
this.type = type;
hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
hashCode = hashCode * 23 + (sql == null ? 0 : sql.GetHashCode());
hashCode = hashCode * 23 + (type == null ? 0 : type.GetHashCode());
}
public override bool Equals(object obj)
{
return Equals(obj as Identity);
}
private readonly string sql;
private readonly int hashCode;
private readonly Type type;
public override int GetHashCode()
{
return hashCode;
}
public bool Equals(Identity other)
{
return other != null && this.type == other.type
&& sql == other.sql;
}
}
static ConcurrentDictionary<Identity, object> cachedSerializers = new ConcurrentDictionary<Identity, object>();
static ConcurrentDictionary<Type, Func<object, List<ParamInfo>>> cachedParamReaders = new ConcurrentDictionary<Type, Func<object, List<ParamInfo>>>();
static Dictionary<Type, SqlDbType> typeMap;
public static List<T> ExecuteMapperQuery<T>(this SqlConnection cnn, string sql, object param = null, SqlTransaction transaction = null)
{
var identity = new Identity(sql, typeof(T));
var rval = new List<T>();
Func<object, List<ParamInfo>> paramInfoGenerator;
List<ParamInfo> paramInfo = null;
if (param != null)
{
if (!cachedParamReaders.TryGetValue(param.GetType(), out paramInfoGenerator))
{
paramInfoGenerator = CreateParamInfoGenerator(param.GetType());
cachedParamReaders[param.GetType()] = paramInfoGenerator;
}
paramInfo = paramInfoGenerator(param);
}
using (var reader = GetReader<T>(cnn, transaction, sql, paramInfo))
{
object oDeserializer;
if (!cachedSerializers.TryGetValue(identity, out oDeserializer))
{
if (typeof(T).IsClass)
{
oDeserializer = GetClassDeserializer<T>(reader);
}
else
{
oDeserializer = GetStructDeserializer<T>(reader);
}
cachedSerializers[identity] = oDeserializer;
}
Func<SqlDataReader, T> deserializer = (Func<SqlDataReader, T>)oDeserializer;
while (reader.Read())
{
rval.Add(deserializer(reader));
}
// ignore any other grids; note that this might mean we miss exceptions that happen
// late in the TDS stream, but that is bad design anyhow
}
return rval;
}
private static Func<object, List<ParamInfo>> CreateParamInfoGenerator(Type type)
{
DynamicMethod dm = new DynamicMethod("ParamInfo" + Guid.NewGuid().ToString(), typeof(List<ParamInfo>), new Type[] { typeof(object) }, true);
var il = dm.GetILGenerator();
il.DeclareLocal(type); // 0
il.Emit(OpCodes.Ldarg_0); // stack is now [untyped-param]
il.Emit(OpCodes.Unbox_Any, type); // stack is now [typed-param]
il.Emit(OpCodes.Stloc_0);// stack is now empty
il.Emit(OpCodes.Newobj, typeof(List<ParamInfo>).GetConstructor(Type.EmptyTypes)); // stack is now [list]
foreach (var prop in type.GetProperties().OrderBy(p => p.Name))
{
// we want to call list.Add(ParamInfo.Create(string name, SqlDbType type, object val))
il.Emit(OpCodes.Dup); // stack is now [list] [list]
il.Emit(OpCodes.Ldstr, prop.Name); // stack is [list] [list] [name]
il.Emit(OpCodes.Ldc_I4, (int)typeMap[prop.PropertyType]); // stack is [list] [list] [name] [dbtype]
il.Emit(OpCodes.Ldloc_0); // stack is [list] [list] [name] [dbtype] [typed-param]
il.Emit(OpCodes.Callvirt, prop.GetGetMethod()); // stack is [list] [list] [name] [dbtype] [typed-value]
if (prop.PropertyType.IsValueType)
{
il.Emit(OpCodes.Box, prop.PropertyType); // stack is [list] [list] [name] [dbtype] [untyped-value]
}
il.Emit(OpCodes.Call, typeof(ParamInfo).GetMethod("Create", BindingFlags.Static | BindingFlags.Public)); // stack is [list] [list] [param-info]
il.Emit(OpCodes.Callvirt, typeof(List<ParamInfo>).GetMethod("Add", BindingFlags.Public | BindingFlags.Instance)); // stack is [list]
}
il.Emit(OpCodes.Ret);
return (Func<object, List<ParamInfo>>)dm.CreateDelegate(typeof(Func<object, List<ParamInfo>>));
}
private static SqlDataReader GetReader<T>(SqlConnection cnn, SqlTransaction tranaction, string sql, List<ParamInfo> paramInfo)
{
using (var cmd = cnn.CreateCommand())
{
cmd.Transaction = tranaction;
cmd.CommandText = sql;
if (paramInfo != null)
{
foreach (var info in paramInfo)
{
var param = cmd.Parameters.Add("@" + info.Name, info.Type);
param.Value = info.Val ?? DBNull.Value;
param.Direction = ParameterDirection.Input;
if (info.Type == SqlDbType.NVarChar)
{
param.Size = 4000;
}
if (info.Type == SqlDbType.Structured)
{
List<SqlDataRecord> items = new List<SqlDataRecord>();
SqlMetaData[] metadata = { new SqlMetaData("Id", SqlDbType.Int) };
foreach (int id in (IEnumerable<int>)info.Val)
{
SqlDataRecord rec = new SqlDataRecord(metadata);
rec.SetInt32(0, id);
items.Add(rec);
}
param.Direction = ParameterDirection.Input;
param.TypeName = "int_list";
param.Value = items;
}
}
}
return cmd.ExecuteReader();
}
}
private static object GetStructDeserializer<T>(SqlDataReader reader)
{
Func<SqlDataReader, T> deserializer = null;
var type = typeof(T);
if (type == typeof(int))
{
// yuck boxing
deserializer = r => (T)(object)r.GetInt32(0);
}
return deserializer;
}
public static Func<SqlDataReader, T> GetClassDeserializer<T>(SqlDataReader reader)
{
DynamicMethod dm = new DynamicMethod("Deserialize" + Guid.NewGuid().ToString(), typeof(T), new Type[] { typeof(SqlDataReader) }, true);
var il = dm.GetILGenerator();
var properties = typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => new { Name = p.Name, Setter = p.GetSetMethod(), Type = p.PropertyType })
.Where(info => info.Setter != null)
.ToList();
var names = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
names.Add(reader.GetName(i));
}
var setters = (
from n in names
select new { Name = n, Info = properties.FirstOrDefault(p => p.Name == n) }
).ToList();
var getItem = typeof(SqlDataReader).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.GetIndexParameters().Any() && p.GetIndexParameters()[0].ParameterType == typeof(int))
.Select(p => p.GetGetMethod()).First();
int index = 0;
// stack is empty
il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes)); // stack is now [target]
foreach (var item in setters)
{
if (item.Info != null)
{
il.Emit(OpCodes.Dup); // stack is now [target][target]
Label isDbNullLabel = il.DefineLabel();
Label finishLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0); // stack is now [target][target][reader]
EmitInt32(il, index++); // stack is now [target][target][reader][index]
il.Emit(OpCodes.Callvirt, getItem); // stack is now [target][target][value-as-object]
il.Emit(OpCodes.Dup); // stack is now [target][target][value][value]
il.Emit(OpCodes.Isinst, typeof(DBNull)); // stack is now [target][target][value-as-object][DBNull or null]
il.Emit(OpCodes.Brtrue_S, isDbNullLabel); // stack is now [target][target][value-as-object]
il.Emit(OpCodes.Unbox_Any, item.Info.Type); // stack is now [target][target][typed-value]
il.Emit(OpCodes.Callvirt, item.Info.Setter); // stack is now [target]
il.Emit(OpCodes.Br_S, finishLabel); // stack is now [target]
il.MarkLabel(isDbNullLabel); // incoming stack: [target][target][value]
il.Emit(OpCodes.Pop); // stack is now [target][target]
il.Emit(OpCodes.Pop); // stack is now [target]
il.MarkLabel(finishLabel);
}
}
il.Emit(OpCodes.Ret); // stack is empty
return (Func<SqlDataReader, T>)dm.CreateDelegate(typeof(Func<SqlDataReader, T>));
}
private static void EmitInt32(ILGenerator il, int value)
{
switch (value)
{
case -1: il.Emit(OpCodes.Ldc_I4_M1); break;
case 0: il.Emit(OpCodes.Ldc_I4_0); break;
case 1: il.Emit(OpCodes.Ldc_I4_1); break;
case 2: il.Emit(OpCodes.Ldc_I4_2); break;
case 3: il.Emit(OpCodes.Ldc_I4_3); break;
case 4: il.Emit(OpCodes.Ldc_I4_4); break;
case 5: il.Emit(OpCodes.Ldc_I4_5); break;
case 6: il.Emit(OpCodes.Ldc_I4_6); break;
case 7: il.Emit(OpCodes.Ldc_I4_7); break;
case 8: il.Emit(OpCodes.Ldc_I4_8); break;
default: il.Emit(OpCodes.Ldc_I4, value); break;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A2A80512-11F4-4028-A995-505463632C84}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SqlMapper</RootNamespace>
<AssemblyName>Smackdown</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Entity" />
<Reference Include="System.Data.Linq" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="EntityFramework\Model.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Model.edmx</DependentUpon>
</Compile>
<Compile Include="Linq2Sql\DataClasses.designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>DataClasses.dbml</DependentUpon>
</Compile>
<Compile Include="Linq2Sql\Post.cs" />
<Compile Include="PerformanceTests.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<Compile Include="SqlMapper.cs" />
<Compile Include="Tests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<EntityDeploy Include="EntityFramework\Model.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>Model.Designer.cs</LastGenOutput>
</EntityDeploy>
<None Include="Linq2Sql\DataClasses.dbml">
<Generator>MSLinqToSQLGenerator</Generator>
<LastGenOutput>DataClasses.designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</None>
<None Include="nhibernate\nhibernate-configuration.xsd">
<SubType>Designer</SubType>
</None>
<None Include="nhibernate\nhibernate-mapping.xsd">
<SubType>Designer</SubType>
</None>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{3259AA49-8AA1-44D3-9025-A0B520596A8C}" />
</ItemGroup>
<ItemGroup>
<None Include="Linq2Sql\DataClasses.dbml.layout">
<DependentUpon>DataClasses.dbml</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<Content Include="nhibernate\Iesi.Collections.dll" />
<Content Include="nhibernate\Iesi.Collections.pdb" />
<Content Include="nhibernate\Iesi.Collections.xml" />
<Content Include="nhibernate\NHibernate.dll" />
<Content Include="nhibernate\NHibernate.pdb" />
<Content Include="nhibernate\NHibernate.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlMapper", "SqlMapper.csproj", "{A2A80512-11F4-4028-A995-505463632C84}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A2A80512-11F4-4028-A995-505463632C84}.Debug|x86.ActiveCfg = Debug|x86
{A2A80512-11F4-4028-A995-505463632C84}.Debug|x86.Build.0 = Debug|x86
{A2A80512-11F4-4028-A995-505463632C84}.Release|x86.ActiveCfg = Release|x86
{A2A80512-11F4-4028-A995-505463632C84}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace SqlMapper
{
class Tests
{
void AssertEquals(object a, object b)
{
if (!a.Equals(b))
{
throw new ApplicationException(string.Format("{0} should be equals to {1}",a,b));
}
}
SqlConnection connection = Program.GetOpenConnection();
public void SelectListInt()
{
var items = connection.ExecuteMapperQuery<int>("select 1 union all select 2 union all select 3").ToList();
AssertEquals(items[0], 1);
AssertEquals(items[1], 2);
AssertEquals(items[2], 3);
}
public void PassInIntArray()
{
var items = connection.ExecuteMapperQuery<int>("select * from @Ids", new {Ids = new int[] {1,2,3} }).ToList();
AssertEquals(items[0], 1);
AssertEquals(items[1], 2);
AssertEquals(items[2], 3);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections></configSections>
<connectionStrings>
<add name="Smackdown.Properties.Settings.tempdbConnectionString" connectionString="Data Source=.;Initial Catalog=tempdb;Integrated Security=True" providerName="System.Data.SqlClient" /><add name="tempdbEntities" connectionString="metadata=res://*/EntityFramework.Model.csdl|res://*/EntityFramework.Model.ssdl|res://*/EntityFramework.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=tempdb;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /><add name="tempdbEntities1" connectionString="metadata=res://*/EntityFramework.Model.csdl|res://*/EntityFramework.Model.ssdl|res://*/EntityFramework.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=tempdb;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
</configuration>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment