# // L2ST4 - LINQ to SQL templates for T4 v0.82 - http://www.codeplex.com/l2st4
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)
#><#@ template language="C#" hostspecific="True"
#><#@ include file="L2ST4.ttinclude"
#><#@ output extension=".generated.cs"
#><# // Set options here
var options = new {
DbmlFileName = Host.TemplateFile.Replace(".tt",".dbml"), // Which DBML file to operate on (same filename as template)
SerializeDataContractSP1 = true, // Emit SP1 DataContract serializer attributes
FilePerEntity = false, // Put each class into a separate file
StoredProcedureConcurrency = false, // Table updates via an SP require @@rowcount to be returned to enable concurrency
EntityFilePath = Path.GetDirectoryName(Host.TemplateFile) // Where to put the files
};
var code = new CSharpCodeLanguage();
var data = new Data(options.DbmlFileName);
var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = options.EntityFilePath };
data.ContextNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedContextNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
data.EntityNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedEntityNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
manager.StartHeader();
#>#pragma warning disable 1591
//------------------------------------------------------------------------------
//
// This code was generated by LINQ to SQL template for T4 C#
// Generated at <#=DateTime.Now#>
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
<#if (data.Functions.Count > 0) {#>
using System.Reflection;
<#}
string dataContractAttributes = (options.SerializeDataContractSP1) ? "IsReference=true" : "";
if (data.Serialization) {#>
using System.Runtime.Serialization;
<#}#>
<# manager.EndHeader();
if(!String.IsNullOrEmpty(data.ContextNamespace)){#>
namespace <#=data.ContextNamespace#>
{
<#}#>
[DatabaseAttribute(Name=@"<#=data.DatabaseName#>")]
<#=code.Format(data.TypeAttributes)#>partial class <#=data.ContextName#> : <#=data.BaseClassName#>
{
private static MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
<# var tableOperations = new List();
foreach(var table in data.Tables)
tableOperations.AddRange(table.Operations);
foreach(Table table in data.Tables)
foreach(OperationType operationType in Enum.GetValues(typeof(OperationType)))
if (!tableOperations.Any(o => (o.Table == table) && (o.Type == operationType))) {#>
partial void <#=operationType#><#=table.BaseClass.Name#>(<#=table.BaseClass.QualifiedName#> instance);
<#}#>
#endregion
#region Construction
<#if (data.ConnectSettingsObject != null) {#>
public <#=data.ContextName#>() :
base(global::<#=data.ConnectSettingsObject#>.Default.<#=data.ConnectSettingsProperty#>, mappingSource)
{
OnCreated();
}
<#}#>
public <#=data.ContextName#>(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public <#=data.ContextName#>(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public <#=data.ContextName#>(string connection, MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public <#=data.ContextName#>(System.Data.IDbConnection connection, MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
#endregion
<#if(data.Tables.Count > 0) {#>
#region Tables
<# foreach(Table table in data.Tables) {
#> <#=code.GetAccess(table.BaseClass.TypeAttributes)#>Table<<#=table.BaseClass.QualifiedName#>> <#=table.Member#>
{
get { return GetTable<<#=table.BaseClass.QualifiedName#>>(); }
}
<# }
#> #endregion
<#}
if (data.Functions.Count > 0) {#>
#region Functions
<# foreach(Function function in data.Functions) {
#>
[Function(Name=@"<#=function.Name#>"<#
if (function.IsComposable) {#>, IsComposable=true<#}
#>)]
<# if (function.Return != null && function.Return.DbType != null) {
#> [return: Parameter(DbType=@"<#=function.Return.DbType#>")]
<# }
if (function.HasMultipleResults) {
foreach(Class class1 in function.Classes) {#>
[ResultType(typeof(<#=class1.QualifiedName#>))]
<# }
}#>
<#=code.Format(function.MemberAttributes)#><#=code.Format(function.ReturnType)#> <#=function.Method#>(<#
foreach(Parameter parameter in function.Parameters) {#>
[Parameter(Name=@"<#=parameter.DbName#>", DbType=@"<#=parameter.DbType#>")] <#=code.Format(parameter.Direction)#><#=code.Format(parameter.Type)#> <#=parameter.Name#><#
if (parameter != function.Parameters.Last()) {#>,<# }
}
#>) {
<# foreach(Parameter outParameter in function.Parameters.Where(p => p.Direction == ParameterDirection.Out)) {#>
<#=outParameter.Name#> = default(<#=code.Format(outParameter.Type)#>);
<# }#>
IExecuteResult result = ExecuteMethodCall(this, (MethodInfo) MethodInfo.GetCurrentMethod()<#=String.Join("", function.Parameters.Select(p => ", " + p.Name).ToArray())#>);
<# int paramIdx = 0;
foreach(Parameter parameter in function.Parameters) {
if (parameter.Direction != ParameterDirection.In) {#>
<#=parameter.Name#> = (<#=code.Format(parameter.Type)#>) result.GetParameterValue(<#=paramIdx#>);
<# }
paramIdx++;
}
#> return (<#=code.Format(function.ReturnType)#>) result.ReturnValue;
}
<# }#>
#endregion
<# if (tableOperations.Count > 0) { #>
#region Table Operations
<# foreach(var operation in tableOperations) { #>
private void <#=operation.Type#><#=operation.Table.BaseClass.Name#>(<#=operation.Table.BaseClass.QualifiedName#> obj) {
<# if (operation.Arguments.Any(a => a.Version == ArgumentVersion.Original)) {
#> var original = <#=operation.Table.Member#>.GetOriginalEntityState(obj);
<# }
int paramIdx = 1;
foreach(var argument in operation.Arguments.Where(a => a.Parameter.Direction != ParameterDirection.In)) {
#> <#=code.Format(argument.Parameter.Type)#> p<#=paramIdx++#> = obj.<#=argument.Member#>;
<# }#>
<# if (options.StoredProcedureConcurrency) {#>var rowCount = <#}#><#=operation.Function.Method#>(<#
paramIdx = 1;
foreach(var argument in operation.Arguments) {
switch(argument.Parameter.Direction) {
case ParameterDirection.InOut: #>ref p<#=paramIdx++#><# break;
case ParameterDirection.Out: #>out p<#=paramIdx++#><# break;
default: #><#=(argument.Version == ArgumentVersion.New) ? "obj" : "original"#>.<#=argument.Member#><# break;
}
if (argument != operation.Arguments.Last()) {#>, <#}
}
#>);
<# if (options.StoredProcedureConcurrency) {#>
if (rowCount != 1) {
throw new ChangeConflictException();
}
<# }
paramIdx = 1;
foreach(var argument in operation.Arguments.Where(a => a.Parameter.Direction != ParameterDirection.In)) {
#> obj.<#=argument.Member#> = p<#=paramIdx++#>.GetValueOrDefault();
<# }#>
}
<#
}
#>
#endregion
<# }
}#>
}
<#if (!String.IsNullOrEmpty(data.ContextNamespace)) {
#>}
<#}
foreach(Table table in data.Tables) {
foreach(TableClass class1 in table.Classes) {
manager.StartBlock(Path.ChangeExtension(class1.Name,".generated.cs"));
if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
namespace <#=data.EntityNamespace#>
{
<# }
if (data.Serialization && class1.IsSerializable) {
#> [DataContract(<#=dataContractAttributes#>)]
<# }
if (class1 == table.BaseClass) {#>
[Table(Name=@"<#=table.Name#>")]
<# foreach(TableClass subclass in data.TableClasses.Where(c => c.Table == table)) {
if (!String.IsNullOrEmpty(subclass.InheritanceCode)) {#>
[InheritanceMapping(Code=@"<#=subclass.InheritanceCode#>", Type=typeof(<#=subclass.Name#>)<# if (subclass.IsInheritanceDefault) {#>, IsDefault=true<#}#>)]
<# }
if (data.Serialization && subclass.IsSerializable) {#>[KnownType(typeof(<#=subclass.Name#>))]<#}
}
#> <#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#> :<#if (!String.IsNullOrEmpty(data.EntityBase)) {#> <#=data.EntityBase#>, <#}#> INotifyPropertyChanging, INotifyPropertyChanged
{
#region Property Change Event Handling
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
<#=code.Format(class1.PropertyChangeAccess)#>void SendPropertyChanging()
{
if (PropertyChanging != null) {
PropertyChanging(this, emptyChangingEventArgs);
}
}
<#=code.Format(class1.PropertyChangeAccess)#>void SendPropertyChanged(String propertyName)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
<# } else {
#> <#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#> : <#=class1.SuperClass.Name#>
{
<# }#>
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(ChangeAction action);
<# if (class1.HasPrimaryKey) {#>
partial void OnCreated();
<# }#>
#endregion
#region Construction
public <#=class1.Name#>()
{
<# if (data.Serialization) {
#> Initialize();
}
private void Initialize()
{
<# }
foreach(Association association in class1.Associations) {
#> <#=association.Storage#> = <#
if (association.IsMany) {
#>new EntitySet<<#=association.Type.Name#>>(attach_<#=association.Member#>, detach_<#=association.Member#>);
<# } else {
#>default(EntityRef<<#=association.Type.Name#>>);
<# }
}
if (class1.HasPrimaryKey) {#>
OnCreated();
<# }#>
}
#endregion
<# int dataMemberIndex = 1;
if (class1.Columns.Count > 0) {
#> #region Column Mappings
<# foreach(Column column in class1.Columns) {#>
partial void On<#=column.Member#>Changing(<#=code.Format(column.Type)#> value);
partial void On<#=column.Member#>Changed();
private <#=code.Format(column.StorageType)#> <#=column.Storage#><# if (column.IsReadOnly) {#> = default(<#=code.Format(column.StorageType)#>)<#}#>;
[Column(Storage=@"<#=column.Storage#>"<#
if (column.Name != column.Member) {#>, Name=@"<#=column.Name#>"<#}
if (column.AutoSync != AutoSync.Default) {#>, AutoSync=AutoSync.<#=column.AutoSync.ToString()#><#}
if (!String.IsNullOrEmpty(column.DbType)) {#>, DbType=@"<#=column.DbType#>"<#}
if (column.IsPrimaryKey) {#>, IsPrimaryKey=true<#}
if (column.IsDiscriminator) {#>, IsDiscriminator=true<#}
if (column.IsDbGenerated) {#>, IsDbGenerated=true<#}
if (column.IsVersion) {#>, IsVersion=true<#}
if (!column.CanBeNull && !column.IsPrimaryKey) {#>, CanBeNull=false<#}
if (column.UpdateCheck != UpdateCheck.Always) {#>, UpdateCheck=UpdateCheck.<#=column.UpdateCheck.ToString()#><#}
if (!String.IsNullOrEmpty(column.Expression)) {#>, Expression=@"<#=column.Expression#>"<#}
#>)]
<# if (data.Serialization && ((column.MemberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)) {
#> [DataMember(Order=<#=dataMemberIndex++#>)]
<# }
#> <#=code.Format(column.MemberAttributes)#><#=code.Format(column.Type)#> <#=column.Member#>
{
get { return <#=column.StorageValue#>; }
<# if (!column.IsReadOnly) { #>
set {
if (<#=column.StorageValue#> != value) {
<# if (column.ForeignKeyAssociations.Count > 0) {#>
if (<#=String.Join(" || ", column.ForeignKeyAssociations.Select(a => a.Storage + ".HasLoadedOrAssignedValue").ToArray())#>) {
throw new ForeignKeyReferenceAlreadyHasValueException();
}
<# }#>
On<#=column.Member#>Changing(value);
SendPropertyChanging();
<#=column.StorageValue#> = value;
SendPropertyChanged("<#=column.Member#>");
On<#=column.Member#>Changed();
}
}
<# }#>
}
<# }#>
#endregion
<# }
bool needsSerializationFlag = class1.IsSerializable && class1.Associations.Any(a => !a.ManagesKeys);
if (class1.Associations.Count > 0) {
#>
#region Associations
<# foreach(Association association in class1.Associations) {#>
private Entity<#=(association.IsMany) ? "Set" : "Ref"#><<#=association.Type.Name#>> <#=association.Storage#>;
[Association(Name=@"<#=association.Name#>"<#
#>, Storage=@"<#=association.Storage#>"<#
if (association.ThisKeyMembers != null) {#>, ThisKey=@"<#=String.Join(",", association.ThisKeyMembers)#>"<#}
if (association.OtherKeyMembers != null) {#>, OtherKey=@"<#=String.Join(",", association.OtherKeyMembers)#>"<#}
if (association.IsForeignKey) {#>, IsForeignKey=true<#}
if (association.IsUnique) {#>, IsUnique=true, IsForeignKey=false<#}
if (association.DeleteOnNull) {#>, DeleteOnNull=true<#}
if (association.DeleteRule != null) {#>, DeleteRule=@"<#=association.DeleteRule #>"<#}
#>)]
<# bool serialization = association.IsSerializable && data.Serialization &&
(options.SerializeDataContractSP1 || !association.ManagesKeys);
if (serialization) {
#> [DataMember(Order=<#=dataMemberIndex++#>, EmitDefaultValue=false)]
<# }
if (!association.IsMany) {#>
<#=code.Format(association.MemberAttributes)#><#=association.Type.Name#> <#=association.Member#>
{
get {
<# if (needsSerializationFlag && serialization) {#>
if (serializing && !<#=association.Storage#>.HasLoadedOrAssignedValue) {
return null;
}
<# }#>
return <#=association.Storage#>.Entity;
}
set {
<#=association.Type.Name#> previousValue = <#=association.Storage#>.Entity;
if ((previousValue != value)<#if (association.OtherSide != null) {#> || (!<#=association.Storage#>.HasLoadedOrAssignedValue)<#}#>) {
SendPropertyChanging();
<# if (association.OtherSide != null) {#>
if (previousValue != null) {
<#=association.Storage#>.Entity = null;
previousValue.<#=association.OtherSide.Member#><#if (!association.OtherSide.IsMany) {#> = null<#} else {#>.Remove(this)<#}#>;
}
<# }
#> <#=association.Storage#>.Entity = value;
<# if (association.OtherSide != null) {#>
if (value != null) {
value.<#=association.OtherSide.Member#><#if (!association.OtherSide.IsMany) {#> = this<#} else {#>.Add(this)<#}#>;
<# if (association.ManagesKeys) {
for(int keyIdx=0;keyIdx
<#=association.ThisKey[keyIdx].Storage#> = value.<#=association.OtherKey[keyIdx].Member#>;
<# }#>
}
else {
<# for(int keyIdx=0;keyIdx <#=association.ThisKey[keyIdx].Storage#> = default(<#=code.Format(association.ThisKey[keyIdx].Type)#>);
<# }
}
#> }
<# }#>
SendPropertyChanged("<#=association.Member#>");
}
}
}
<# } else {#>
<#=code.Format(association.MemberAttributes)#>EntitySet<<#=association.Type.Name#>> <#=association.Member#>
{
get {
<# if (needsSerializationFlag && serialization) {#>
if (serializing && !<#=association.Storage#>.HasLoadedOrAssignedValues) {
return null;
}
<# } #>
return <#=association.Storage#>;
}
set {
<#=association.Storage#>.Assign(value);
}
}
private void attach_<#=association.Member#>(<#=association.Type.Name#> entity)
{
SendPropertyChanging();
entity.<#=association.OtherSide.Member#> = this;
}
private void detach_<#=association.Member#>(<#=association.Type.Name#> entity)
{
SendPropertyChanging();
entity.<#=association.OtherSide.Member#> = null;
}
<# }
}#>
#endregion
<# }
if (data.Serialization) {#>
#region Serialization
<# if (needsSerializationFlag) {#>
private bool serializing;
[OnSerializing()]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnSerializing(StreamingContext context)
{
serializing = true;
}
[OnSerialized()]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public void OnSerialized(StreamingContext context)
{
serializing = false;
}
<# }#>
[OnDeserializing()]
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public <#if (class1 != table.BaseClass) {#>new<#}#> void OnDeserializing(StreamingContext context)
{
Initialize();
}
#endregion
<# }
#> }
<# if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
}
<# }
manager.EndBlock();
}
}
if (data.FunctionClasses.Count > 0) {
foreach(FunctionClass class1 in data.FunctionClasses) {
manager.StartBlock(Path.ChangeExtension(class1.Name,".generated.cs"));
if(!String.IsNullOrEmpty(data.EntityNamespace)){#>
namespace <#=data.EntityNamespace#>
{
<# }
if (data.Serialization) {
#> [DataContract(<#=dataContractAttributes#>)]
<# } #>
<#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#>
{
<# int dataMemberIndex = 1;
foreach(Column column in class1.Columns) {#>
private <#=code.Format(column.Type)#> <#=column.Storage#>;
[Column(Storage=@"<#=column.Storage#>"<#
if (column.Name != column.Member) {#>, Name=@"<#=column.Name#>"<#}
if (!String.IsNullOrEmpty(column.DbType)) {#>, DbType=@"<#=column.DbType#>"<#}
if (!column.CanBeNull && !column.IsPrimaryKey) {#>, CanBeNull=false<#}
#>)]
<# if (data.Serialization && ((column.MemberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)) {
#> [DataMember(Order=<#=dataMemberIndex++#>)]
<# }
#> <#=code.Format(column.MemberAttributes)#><#=code.Format(column.Type)#> <#=column.Member#> {
get { return <#=column.Storage#>; }
set {
if (<#=column.Storage#> != value) {
<#=column.Storage#> = value;
}
}
}
<# } #>
}
<# if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
}
<# }
manager.EndBlock();
}
}
manager.StartFooter();#>
#pragma warning restore 1591<#
manager.EndFooter();
manager.Process(options.FilePerEntity);#>