Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB/HeuristicLab.Services.OKB.DataAccess/3.3/OKB.tt @ 4695

Last change on this file since 4695 was 4276, checked in by swagner, 14 years ago

Integrated OKB data access layer (#1166)

File size: 18.3 KB
Line 
1<# // L2ST4 - LINQ to SQL templates for T4 v0.82 - http://www.codeplex.com/l2st4
2// Copyright (c) Microsoft Corporation.  All rights reserved.
3// This source code is made available under the terms of the Microsoft Public License (MS-PL)
4#><#@ template language="C#" hostspecific="True"
5#><#@ include file="L2ST4.ttinclude"
6#><#@ output extension=".generated.cs"
7#><# // Set options here
8var options = new {
9  DbmlFileName = Host.TemplateFile.Replace(".tt",".dbml"), // Which DBML file to operate on (same filename as template)
10  SerializeDataContractSP1 = true, // Emit SP1 DataContract serializer attributes
11  FilePerEntity = false, // Put each class into a separate file
12  StoredProcedureConcurrency = false, // Table updates via an SP require @@rowcount to be returned to enable concurrency
13  EntityFilePath = Path.GetDirectoryName(Host.TemplateFile) // Where to put the files
14};
15var code = new CSharpCodeLanguage();
16var data = new Data(options.DbmlFileName);
17var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = options.EntityFilePath };
18data.ContextNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedContextNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
19data.EntityNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedEntityNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
20manager.StartHeader();
21#>#pragma warning disable 1591
22//------------------------------------------------------------------------------
23// <auto-generated>
24//     This code was generated by LINQ to SQL template for T4 C#
25//     Generated at <#=DateTime.Now#>
26//
27//     Changes to this file may cause incorrect behavior and will be lost if
28//     the code is regenerated.
29// </auto-generated>
30//------------------------------------------------------------------------------
31using System;
32using System.ComponentModel;
33using System.Data.Linq;
34using System.Data.Linq.Mapping;
35<#if (data.Functions.Count > 0) {#>
36using System.Reflection;
37<#}
38string dataContractAttributes = (options.SerializeDataContractSP1) ? "IsReference=true" : "";
39if (data.Serialization) {#>
40using System.Runtime.Serialization;
41<#}#>
42
43<# manager.EndHeader();
44if(!String.IsNullOrEmpty(data.ContextNamespace)){#>
45namespace <#=data.ContextNamespace#>
46{
47<#}#>
48  [DatabaseAttribute(Name=@"<#=data.DatabaseName#>")]
49  <#=code.Format(data.TypeAttributes)#>partial class <#=data.ContextName#> : <#=data.BaseClassName#>
50  {
51    private static MappingSource mappingSource = new AttributeMappingSource();
52   
53    #region Extensibility Method Definitions
54    partial void OnCreated();
55<#  var tableOperations = new List<TableOperation>();
56  foreach(var table in data.Tables)
57    tableOperations.AddRange(table.Operations);
58  foreach(Table table in data.Tables)
59    foreach(OperationType operationType in Enum.GetValues(typeof(OperationType)))
60      if (!tableOperations.Any(o => (o.Table == table) && (o.Type == operationType))) {#>
61    partial void <#=operationType#><#=table.BaseClass.Name#>(<#=table.BaseClass.QualifiedName#> instance);
62<#}#>
63    #endregion
64   
65    #region Construction
66<#if (data.ConnectSettingsObject != null) {#>
67    public <#=data.ContextName#>() :
68      base(global::<#=data.ConnectSettingsObject#>.Default.<#=data.ConnectSettingsProperty#>, mappingSource)
69    {
70      OnCreated();
71    }
72<#}#>
73    public <#=data.ContextName#>(string connection) :
74      base(connection, mappingSource)
75    {
76      OnCreated();
77    }
78   
79    public <#=data.ContextName#>(System.Data.IDbConnection connection) :
80      base(connection, mappingSource)
81    {
82      OnCreated();
83    }
84   
85    public <#=data.ContextName#>(string connection, MappingSource mappingSource) :
86      base(connection, mappingSource)
87    {
88      OnCreated();
89    }
90   
91    public <#=data.ContextName#>(System.Data.IDbConnection connection, MappingSource mappingSource) :
92      base(connection, mappingSource)
93    {
94      OnCreated();
95    }
96    #endregion
97<#if(data.Tables.Count > 0) {#>
98   
99    #region Tables
100<#  foreach(Table table in data.Tables) {
101#>    <#=code.GetAccess(table.BaseClass.TypeAttributes)#>Table<<#=table.BaseClass.QualifiedName#>> <#=table.Member#>
102    {
103      get { return GetTable<<#=table.BaseClass.QualifiedName#>>(); }
104    }
105   
106<#  }
107#>    #endregion
108<#}
109if (data.Functions.Count > 0) {#>
110   
111    #region Functions
112<#  foreach(Function function in data.Functions) {
113#>
114    [Function(Name=@"<#=function.Name#>"<#
115    if (function.IsComposable) {#>, IsComposable=true<#}
116    #>)]
117<#    if (function.Return != null && function.Return.DbType != null) {
118#>    [return: Parameter(DbType=@"<#=function.Return.DbType#>")]
119<#    }
120    if (function.HasMultipleResults) {
121      foreach(Class class1 in function.Classes) {#>
122    [ResultType(typeof(<#=class1.QualifiedName#>))]
123<#      }
124    }#>
125    <#=code.Format(function.MemberAttributes)#><#=code.Format(function.ReturnType)#> <#=function.Method#>(<#
126    foreach(Parameter parameter in function.Parameters) {#>
127
128          [Parameter(Name=@"<#=parameter.DbName#>", DbType=@"<#=parameter.DbType#>")] <#=code.Format(parameter.Direction)#><#=code.Format(parameter.Type)#> <#=parameter.Name#><#
129      if (parameter != function.Parameters.Last()) {#>,<# }
130    }
131    #>) {
132<#    foreach(Parameter outParameter in function.Parameters.Where(p => p.Direction == ParameterDirection.Out)) {#>
133      <#=outParameter.Name#> = default(<#=code.Format(outParameter.Type)#>);
134<#    }#>
135      IExecuteResult result = ExecuteMethodCall(this, (MethodInfo) MethodInfo.GetCurrentMethod()<#=String.Join("", function.Parameters.Select(p => ", " + p.Name).ToArray())#>);
136<#    int paramIdx = 0;
137    foreach(Parameter parameter in function.Parameters) {
138      if (parameter.Direction != ParameterDirection.In) {#>
139      <#=parameter.Name#> = (<#=code.Format(parameter.Type)#>) result.GetParameterValue(<#=paramIdx#>);
140<#      }
141      paramIdx++;
142    }
143#>      return (<#=code.Format(function.ReturnType)#>) result.ReturnValue;
144    }
145   
146<#  }#>
147    #endregion
148   
149<#  if (tableOperations.Count > 0) { #>
150    #region Table Operations
151<#    foreach(var operation in tableOperations) { #>
152    private void <#=operation.Type#><#=operation.Table.BaseClass.Name#>(<#=operation.Table.BaseClass.QualifiedName#> obj) {
153<#      if (operation.Arguments.Any(a => a.Version == ArgumentVersion.Original)) {
154#>      var original = <#=operation.Table.Member#>.GetOriginalEntityState(obj);
155<#      }
156      int paramIdx = 1;
157      foreach(var argument in operation.Arguments.Where(a => a.Parameter.Direction != ParameterDirection.In)) {
158#>      <#=code.Format(argument.Parameter.Type)#> p<#=paramIdx++#> = obj.<#=argument.Member#>;
159<#      }#>
160      <# if (options.StoredProcedureConcurrency) {#>var rowCount = <#}#><#=operation.Function.Method#>(<#
161      paramIdx = 1;
162      foreach(var argument in operation.Arguments) {
163        switch(argument.Parameter.Direction) {
164          case ParameterDirection.InOut: #>ref p<#=paramIdx++#><# break;
165          case ParameterDirection.Out: #>out p<#=paramIdx++#><# break;
166          default: #><#=(argument.Version == ArgumentVersion.New) ? "obj" : "original"#>.<#=argument.Member#><# break;
167        }
168      if (argument != operation.Arguments.Last()) {#>, <#}
169      }
170      #>);
171<#      if (options.StoredProcedureConcurrency) {#>
172      if (rowCount != 1) {
173        throw new ChangeConflictException();
174      }
175<#      }
176      paramIdx = 1;
177      foreach(var argument in operation.Arguments.Where(a => a.Parameter.Direction != ParameterDirection.In)) {
178#>      obj.<#=argument.Member#> = p<#=paramIdx++#>.GetValueOrDefault();
179<#      }#>
180    }
181   
182<#
183    }
184#>
185    #endregion
186<#  }
187}#>
188  }
189<#if (!String.IsNullOrEmpty(data.ContextNamespace)) {
190#>}
191<#}
192foreach(Table table in data.Tables) {
193  foreach(TableClass class1 in table.Classes) {
194    manager.StartBlock(Path.ChangeExtension(class1.Name,".generated.cs"));
195    if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
196
197namespace <#=data.EntityNamespace#>
198{
199<#    }
200    if (data.Serialization && class1.IsSerializable) {
201#>  [DataContract(<#=dataContractAttributes#>)]
202<#    }
203    if (class1 == table.BaseClass) {#>
204  [Table(Name=@"<#=table.Name#>")]
205<#      foreach(TableClass subclass in data.TableClasses.Where(c => c.Table == table)) {
206        if (!String.IsNullOrEmpty(subclass.InheritanceCode)) {#>
207  [InheritanceMapping(Code=@"<#=subclass.InheritanceCode#>", Type=typeof(<#=subclass.Name#>)<# if (subclass.IsInheritanceDefault) {#>, IsDefault=true<#}#>)]
208<#        }
209        if (data.Serialization && subclass.IsSerializable) {#>[KnownType(typeof(<#=subclass.Name#>))]<#}
210      }
211#>  <#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#> :<#if (!String.IsNullOrEmpty(data.EntityBase)) {#> <#=data.EntityBase#>, <#}#> INotifyPropertyChanging, INotifyPropertyChanged
212  {
213    #region Property Change Event Handling
214    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
215   
216    public event PropertyChangingEventHandler PropertyChanging;
217    public event PropertyChangedEventHandler PropertyChanged;
218   
219    <#=code.Format(class1.PropertyChangeAccess)#>void SendPropertyChanging()
220    {
221      if (PropertyChanging != null) {
222        PropertyChanging(this, emptyChangingEventArgs);
223      }
224    }
225     
226    <#=code.Format(class1.PropertyChangeAccess)#>void SendPropertyChanged(String propertyName)
227    {
228      if (PropertyChanged != null) {
229        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
230      }
231    }
232    #endregion
233   
234<#    } else {
235#>  <#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#> : <#=class1.SuperClass.Name#>
236  {
237<#    }#>
238    #region Extensibility Method Definitions
239    partial void OnLoaded();
240    partial void OnValidate(ChangeAction action);
241<#    if (class1.HasPrimaryKey) {#>
242    partial void OnCreated();
243<#    }#>
244    #endregion
245
246    #region Construction
247    public <#=class1.Name#>()
248    {
249<#    if (data.Serialization) {
250#>      Initialize();
251    }
252   
253    private void Initialize()
254    {
255<#    }
256    foreach(Association association in class1.Associations) {
257#>      <#=association.Storage#> = <#
258      if (association.IsMany) {
259        #>new EntitySet<<#=association.Type.Name#>>(attach_<#=association.Member#>, detach_<#=association.Member#>);
260<#      } else {
261        #>default(EntityRef<<#=association.Type.Name#>>);
262<#      }
263    }
264    if (class1.HasPrimaryKey) {#>
265      OnCreated();
266<#    }#>
267    }
268    #endregion
269
270<#    int dataMemberIndex = 1;
271    if (class1.Columns.Count > 0) {
272#>    #region Column Mappings
273<#      foreach(Column column in class1.Columns) {#>
274    partial void On<#=column.Member#>Changing(<#=code.Format(column.Type)#> value);
275    partial void On<#=column.Member#>Changed();
276    private <#=code.Format(column.StorageType)#> <#=column.Storage#><# if (column.IsReadOnly) {#> = default(<#=code.Format(column.StorageType)#>)<#}#>;
277    [Column(Storage=@"<#=column.Storage#>"<#
278        if (column.Name != column.Member) {#>, Name=@"<#=column.Name#>"<#}
279        if (column.AutoSync != AutoSync.Default) {#>, AutoSync=AutoSync.<#=column.AutoSync.ToString()#><#}
280        if (!String.IsNullOrEmpty(column.DbType)) {#>, DbType=@"<#=column.DbType#>"<#}
281        if (column.IsPrimaryKey) {#>, IsPrimaryKey=true<#}
282        if (column.IsDiscriminator) {#>, IsDiscriminator=true<#}
283        if (column.IsDbGenerated) {#>, IsDbGenerated=true<#}
284        if (column.IsVersion) {#>, IsVersion=true<#}
285        if (!column.CanBeNull && !column.IsPrimaryKey) {#>, CanBeNull=false<#}
286        if (column.UpdateCheck != UpdateCheck.Always) {#>, UpdateCheck=UpdateCheck.<#=column.UpdateCheck.ToString()#><#}
287        if (!String.IsNullOrEmpty(column.Expression)) {#>, Expression=@"<#=column.Expression#>"<#}
288    #>)]
289<#        if (data.Serialization && ((column.MemberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)) {
290#>    [DataMember(Order=<#=dataMemberIndex++#>)]
291<#        }
292#>    <#=code.Format(column.MemberAttributes)#><#=code.Format(column.Type)#> <#=column.Member#>
293    {
294      get { return <#=column.StorageValue#>; }
295<#        if (!column.IsReadOnly) { #>
296      set {
297        if (<#=column.StorageValue#> != value) {
298<#          if (column.ForeignKeyAssociations.Count > 0) {#>
299          if (<#=String.Join(" || ", column.ForeignKeyAssociations.Select(a => a.Storage + ".HasLoadedOrAssignedValue").ToArray())#>) {
300            throw new ForeignKeyReferenceAlreadyHasValueException();
301          }
302<#          }#>
303          On<#=column.Member#>Changing(value);
304          SendPropertyChanging();
305          <#=column.StorageValue#> = value;
306          SendPropertyChanged("<#=column.Member#>");
307          On<#=column.Member#>Changed();
308        }
309      }
310<#        }#>
311    }
312   
313<#      }#>
314    #endregion
315<#    }
316    bool needsSerializationFlag = class1.IsSerializable && class1.Associations.Any(a => !a.ManagesKeys);
317    if (class1.Associations.Count > 0) {
318#>   
319    #region Associations
320<#      foreach(Association association in class1.Associations) {#>
321    private Entity<#=(association.IsMany) ? "Set" : "Ref"#><<#=association.Type.Name#>> <#=association.Storage#>;
322    [Association(Name=@"<#=association.Name#>"<#
323      #>, Storage=@"<#=association.Storage#>"<#
324        if (association.ThisKeyMembers != null) {#>, ThisKey=@"<#=String.Join(",", association.ThisKeyMembers)#>"<#}
325        if (association.OtherKeyMembers != null) {#>, OtherKey=@"<#=String.Join(",", association.OtherKeyMembers)#>"<#}
326        if (association.IsForeignKey) {#>, IsForeignKey=true<#}
327        if (association.IsUnique) {#>, IsUnique=true, IsForeignKey=false<#}
328        if (association.DeleteOnNull) {#>, DeleteOnNull=true<#}
329        if (association.DeleteRule != null) {#>, DeleteRule=@"<#=association.DeleteRule #>"<#}
330    #>)]
331<#        bool serialization = association.IsSerializable && data.Serialization &&
332          (options.SerializeDataContractSP1 || !association.ManagesKeys);
333        if (serialization) {
334#>    [DataMember(Order=<#=dataMemberIndex++#>, EmitDefaultValue=false)]
335<#        }
336        if (!association.IsMany) {#>
337    <#=code.Format(association.MemberAttributes)#><#=association.Type.Name#> <#=association.Member#>
338    {
339      get {
340<#          if (needsSerializationFlag && serialization) {#>
341        if (serializing && !<#=association.Storage#>.HasLoadedOrAssignedValue) {
342          return null;
343        }
344<#          }#>
345        return <#=association.Storage#>.Entity;
346      }
347      set {
348        <#=association.Type.Name#> previousValue = <#=association.Storage#>.Entity;
349        if ((previousValue != value)<#if (association.OtherSide != null) {#> || (!<#=association.Storage#>.HasLoadedOrAssignedValue)<#}#>) {
350          SendPropertyChanging();
351<#          if (association.OtherSide != null) {#>
352          if (previousValue != null) {
353            <#=association.Storage#>.Entity = null;
354            previousValue.<#=association.OtherSide.Member#><#if (!association.OtherSide.IsMany) {#> = null<#} else {#>.Remove(this)<#}#>;
355          }
356<#          }
357#>          <#=association.Storage#>.Entity = value;
358<#          if (association.OtherSide != null) {#>
359          if (value != null) {
360            value.<#=association.OtherSide.Member#><#if (!association.OtherSide.IsMany) {#> = this<#} else {#>.Add(this)<#}#>;
361<#            if (association.ManagesKeys) {
362              for(int keyIdx=0;keyIdx<association.ThisKey.Count();keyIdx++) {#>
363            <#=association.ThisKey[keyIdx].Storage#> = value.<#=association.OtherKey[keyIdx].Member#>;
364<#              }#>
365          }
366          else {
367<#              for(int keyIdx=0;keyIdx<association.ThisKey.Count();keyIdx++) {
368#>            <#=association.ThisKey[keyIdx].Storage#> = default(<#=code.Format(association.ThisKey[keyIdx].Type)#>);
369<#              }
370            }
371#>          }
372<#          }#>
373          SendPropertyChanged("<#=association.Member#>");
374        }
375      }
376    }
377
378<#        } else {#>
379    <#=code.Format(association.MemberAttributes)#>EntitySet<<#=association.Type.Name#>> <#=association.Member#>
380    {
381      get {
382<#          if (needsSerializationFlag && serialization) {#>
383        if (serializing && !<#=association.Storage#>.HasLoadedOrAssignedValues) {
384          return null;
385        }
386<#          } #>
387        return <#=association.Storage#>;
388      }
389      set {
390        <#=association.Storage#>.Assign(value);
391      }
392    }
393
394    private void attach_<#=association.Member#>(<#=association.Type.Name#> entity)
395    {
396      SendPropertyChanging();
397      entity.<#=association.OtherSide.Member#> = this;
398    }
399   
400    private void detach_<#=association.Member#>(<#=association.Type.Name#> entity)
401    {
402      SendPropertyChanging();
403      entity.<#=association.OtherSide.Member#> = null;
404    }
405<#        }
406      }#>
407    #endregion
408<#    }
409    if (data.Serialization) {#>
410   
411    #region Serialization
412<#      if (needsSerializationFlag) {#>
413    private bool serializing;
414   
415    [OnSerializing()]
416    [EditorBrowsableAttribute(EditorBrowsableState.Never)]
417    public void OnSerializing(StreamingContext context)
418    {
419      serializing = true;
420    }
421   
422    [OnSerialized()]
423    [EditorBrowsableAttribute(EditorBrowsableState.Never)]
424    public void OnSerialized(StreamingContext context)
425    {
426      serializing = false;
427    }
428   
429<#      }#>
430    [OnDeserializing()]
431    [EditorBrowsableAttribute(EditorBrowsableState.Never)]
432    public <#if (class1 != table.BaseClass) {#>new<#}#> void OnDeserializing(StreamingContext context)
433    {
434      Initialize();
435    }
436    #endregion
437<#    }
438#>  }
439<#    if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
440}
441<#    }
442    manager.EndBlock();
443  }
444}
445if (data.FunctionClasses.Count > 0) {
446  foreach(FunctionClass class1 in data.FunctionClasses) {
447    manager.StartBlock(Path.ChangeExtension(class1.Name,".generated.cs"));
448    if(!String.IsNullOrEmpty(data.EntityNamespace)){#>
449
450namespace <#=data.EntityNamespace#>
451{
452<#    }
453    if (data.Serialization) {
454#>  [DataContract(<#=dataContractAttributes#>)]
455<#    } #>
456  <#=code.Format(class1.TypeAttributes)#>partial class <#=class1.Name#>
457  {
458<#    int dataMemberIndex = 1;
459    foreach(Column column in class1.Columns) {#>
460    private <#=code.Format(column.Type)#> <#=column.Storage#>;
461    [Column(Storage=@"<#=column.Storage#>"<#
462        if (column.Name != column.Member) {#>, Name=@"<#=column.Name#>"<#}
463        if (!String.IsNullOrEmpty(column.DbType)) {#>, DbType=@"<#=column.DbType#>"<#}
464        if (!column.CanBeNull && !column.IsPrimaryKey) {#>, CanBeNull=false<#}
465    #>)]
466<#      if (data.Serialization && ((column.MemberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)) {
467#>    [DataMember(Order=<#=dataMemberIndex++#>)]
468<#      }
469#>    <#=code.Format(column.MemberAttributes)#><#=code.Format(column.Type)#> <#=column.Member#> {
470      get { return <#=column.Storage#>; }
471      set {
472        if (<#=column.Storage#> != value) {
473          <#=column.Storage#> = value;
474        }
475      }
476    }
477<#    } #>
478  }
479<#    if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
480}
481<#    }
482    manager.EndBlock();
483  }
484}
485manager.StartFooter();#>
486#pragma warning restore 1591<#
487manager.EndFooter();
488manager.Process(options.FilePerEntity);#>
Note: See TracBrowser for help on using the repository browser.