This commit is contained in:
yubaolee
2017-11-29 18:26:36 +08:00
parent 503f92d68e
commit e36664d5f6
27 changed files with 3565 additions and 3515 deletions

View File

@@ -1,89 +1,89 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="EntityContext" Type="SchemaMapper.EntityContext" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
<%@ Property Name="InterfaceMode" Type="Boolean" Default="False" Optional="True" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Data.Entity;
using System.Collections.Generic;
using <%= EntityNamespace %>;
using <%= MappingNamespace %>;
namespace <%= ContextNamespace %>
{
<% if (InterfaceMode) { %>
public interface IDbContext : IDisposable
{
System.Data.Entity.Database Database { get; }
System.Data.Entity.Infrastructure.DbChangeTracker ChangeTracker { get; }
System.Data.Entity.Infrastructure.DbContextConfiguration Configuration { get; }
System.Data.Entity.Infrastructure.DbEntityEntry Entry(object entity);
System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
IEnumerable<System.Data.Entity.Validation.DbEntityValidationResult> GetValidationErrors();
System.Data.Entity.DbSet Set(Type entityType);
System.Data.Entity.IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
public partial interface I<%= EntityContext.ClassName.ToSafeName() %> : IDbContext
{
<% foreach(var p in EntityContext.Entities) { %>
System.Data.Entity.IDbSet<<%= EntityNamespace %>.<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
}
<% } // if interface %>
public partial class <%= EntityContext.ClassName.ToSafeName() %>: DbContext<%= InterfaceMode ? ", I" + EntityContext.ClassName.ToSafeName() : string.Empty %>
{
static <%= EntityContext.ClassName.ToSafeName() %>()
{
Database.SetInitializer< <%= EntityContext.ClassName.ToSafeName() %>>(null);
}
public <%= EntityContext.ClassName.ToSafeName() %>()
:base("Name=<%= EntityContext.ClassName.ToSafeName() %>")
{ }
public <%= EntityContext.ClassName.ToSafeName() %>(string nameOrConnectionString)
: base(nameOrConnectionString)
{ }
<% foreach(var p in EntityContext.Entities) { %>
public System.Data.Entity.<%= InterfaceMode ? "I" : "" %>DbSet<<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% if (InterfaceMode) { %>
System.Data.Entity.IDbSet<TEntity> IDbContext.Set<TEntity>()
{
return base.Set<TEntity>();
}
<% } // if interface %>
}
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="EntityContext" Type="SchemaMapper.EntityContext" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
<%@ Property Name="InterfaceMode" Type="Boolean" Default="False" Optional="True" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Data.Entity;
using System.Collections.Generic;
using <%= EntityNamespace %>;
using <%= MappingNamespace %>;
namespace <%= ContextNamespace %>
{
<% if (InterfaceMode) { %>
public interface IDbContext : IDisposable
{
System.Data.Entity.Database Database { get; }
System.Data.Entity.Infrastructure.DbChangeTracker ChangeTracker { get; }
System.Data.Entity.Infrastructure.DbContextConfiguration Configuration { get; }
System.Data.Entity.Infrastructure.DbEntityEntry Entry(object entity);
System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
IEnumerable<System.Data.Entity.Validation.DbEntityValidationResult> GetValidationErrors();
System.Data.Entity.DbSet Set(Type entityType);
System.Data.Entity.IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
public partial interface I<%= EntityContext.ClassName.ToSafeName() %> : IDbContext
{
<% foreach(var p in EntityContext.Entities) { %>
System.Data.Entity.IDbSet<<%= EntityNamespace %>.<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
}
<% } // if interface %>
public partial class <%= EntityContext.ClassName.ToSafeName() %>: DbContext<%= InterfaceMode ? ", I" + EntityContext.ClassName.ToSafeName() : string.Empty %>
{
static <%= EntityContext.ClassName.ToSafeName() %>()
{
Database.SetInitializer< <%= EntityContext.ClassName.ToSafeName() %>>(null);
}
public <%= EntityContext.ClassName.ToSafeName() %>()
:base("Name=<%= EntityContext.ClassName.ToSafeName() %>")
{ }
public <%= EntityContext.ClassName.ToSafeName() %>(string nameOrConnectionString)
: base(nameOrConnectionString)
{ }
<% foreach(var p in EntityContext.Entities) { %>
public System.Data.Entity.<%= InterfaceMode ? "I" : "" %>DbSet<<%= p.ClassName.ToSafeName() %>> <%= p.ContextName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% if (InterfaceMode) { %>
System.Data.Entity.IDbSet<TEntity> IDbContext.Set<TEntity>()
{
return base.Set<TEntity>();
}
<% } // if interface %>
}
}

View File

@@ -1,72 +1,72 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity"
Type="SchemaMapper.Entity" %>
<%@ Property Name="EntityNamespace"
Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace <%= EntityNamespace %>
{
/// <summary>
/// <%= Entity.Description %>
/// </summary>
public partial class <%= Entity.ClassName.ToSafeName() %> : Entity
{
public <%= Entity.ClassName.ToSafeName() %>()
{
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
string type = p.SystemType.ToNullableType(p.IsNullable == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= DateTime.Now;");
} // foreach %>
<% foreach(var r in Entity.Relationships.Where(e => e.ThisCardinality == Cardinality.Many)) { %>
<%= r.ThisPropertyName.ToSafeName() %> = new List<<%= r.OtherEntity.ToSafeName() %>>();
<% } // foreach %>
}
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
%>
/// <summary>
/// <%=p.Description %>
/// </summary>
public <%= p.SystemType.ToNullableType(p.IsNullable == true) %> <%= p.PropertyName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% foreach(var r in Entity.Relationships) { %>
<% if(r.ThisCardinality == Cardinality.Many) { %>
public virtual ICollection<<%= r.OtherEntity.ToSafeName() %>> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } else { %>
public virtual <%= r.OtherEntity.ToSafeName() %> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } %>
<% } // foreach %>
}
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity"
Type="SchemaMapper.Entity" %>
<%@ Property Name="EntityNamespace"
Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace <%= EntityNamespace %>
{
/// <summary>
/// <%= Entity.Description %>
/// </summary>
public partial class <%= Entity.ClassName.ToSafeName() %> : Entity
{
public <%= Entity.ClassName.ToSafeName() %>()
{
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
string type = p.SystemType.ToNullableType(p.IsNullable == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= DateTime.Now;");
} // foreach %>
<% foreach(var r in Entity.Relationships.Where(e => e.ThisCardinality == Cardinality.Many)) { %>
<%= r.ThisPropertyName.ToSafeName() %> = new List<<%= r.OtherEntity.ToSafeName() %>>();
<% } // foreach %>
}
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
%>
/// <summary>
/// <%=p.Description %>
/// </summary>
public <%= p.SystemType.ToNullableType(p.IsNullable == true) %> <%= p.PropertyName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% foreach(var r in Entity.Relationships) { %>
<% if(r.ThisCardinality == Cardinality.Many) { %>
public virtual ICollection<<%= r.OtherEntity.ToSafeName() %>> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } else { %>
public virtual <%= r.OtherEntity.ToSafeName() %> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } %>
<% } // foreach %>
}
}

View File

@@ -1,187 +1,187 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeSmith.Engine;
namespace SchemaMapper
{
public enum CodeLanguage
{
CSharp,
VisualBasic
}
public static class Extensions
{
private static readonly HashSet<string> _csharpKeywords;
private static readonly HashSet<string> _visualBasicKeywords;
private static readonly Dictionary<string, string> _csharpTypeAlias;
static Extensions()
{
_csharpKeywords = new HashSet<string>(StringComparer.Ordinal)
{
"as", "do", "if", "in", "is",
"for", "int", "new", "out", "ref", "try",
"base", "bool", "byte", "case", "char", "else", "enum", "goto", "lock", "long", "null", "this", "true", "uint", "void",
"break", "catch", "class", "const", "event", "false", "fixed", "float", "sbyte", "short", "throw", "ulong", "using", "while",
"double", "extern", "object", "params", "public", "return", "sealed", "sizeof", "static", "string", "struct", "switch", "typeof", "unsafe", "ushort",
"checked", "decimal", "default", "finally", "foreach", "private", "virtual",
"abstract", "continue", "delegate", "explicit", "implicit", "internal", "operator", "override", "readonly", "volatile",
"__arglist", "__makeref", "__reftype", "interface", "namespace", "protected", "unchecked",
"__refvalue", "stackalloc"
};
_visualBasicKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"as", "do", "if", "in", "is", "me", "of", "on", "or", "to",
"and", "dim", "end", "for", "get", "let", "lib", "mod", "new", "not", "rem", "set", "sub", "try", "xor",
"ansi", "auto", "byte", "call", "case", "cdbl", "cdec", "char", "cint", "clng", "cobj", "csng", "cstr", "date", "each", "else",
"enum", "exit", "goto", "like", "long", "loop", "next", "step", "stop", "then", "true", "wend", "when", "with",
"alias", "byref", "byval", "catch", "cbool", "cbyte", "cchar", "cdate", "class", "const", "ctype", "cuint", "culng", "endif", "erase", "error",
"event", "false", "gosub", "isnot", "redim", "sbyte", "short", "throw", "ulong", "until", "using", "while",
"csbyte", "cshort", "double", "elseif", "friend", "global", "module", "mybase", "object", "option", "orelse", "public", "resume", "return", "select", "shared",
"single", "static", "string", "typeof", "ushort",
"andalso", "boolean", "cushort", "decimal", "declare", "default", "finally", "gettype", "handles", "imports", "integer", "myclass", "nothing", "partial", "private", "shadows",
"trycast", "unicode", "variant",
"assembly", "continue", "delegate", "function", "inherits", "operator", "optional", "preserve", "property", "readonly", "synclock", "uinteger", "widening",
"addressof", "interface", "namespace", "narrowing", "overloads", "overrides", "protected", "structure", "writeonly",
"addhandler", "directcast", "implements", "paramarray", "raiseevent", "withevents",
"mustinherit", "overridable",
"mustoverride",
"removehandler",
"class_finalize", "notinheritable", "notoverridable",
"class_initialize"
};
_csharpTypeAlias = new Dictionary<string, string>(16)
{
{"System.Int16", "short"},
{"System.Int32", "int"},
{"System.Int64", "long"},
{"System.String", "string"},
{"System.Object", "object"},
{"System.Boolean", "bool"},
{"System.Void", "void"},
{"System.Char", "char"},
{"System.Byte", "byte"},
{"System.UInt16", "ushort"},
{"System.UInt32", "uint"},
{"System.UInt64", "ulong"},
{"System.SByte", "sbyte"},
{"System.Single", "float"},
{"System.Double", "double"},
{"System.Decimal", "decimal"}
};
}
public static string ToCamelCase(this string name)
{
return StringUtil.ToCamelCase(name);
}
public static string ToPascalCase(this string name)
{
return StringUtil.ToPascalCase(name);
}
public static string ToFieldName(this string name)
{
return "_" + StringUtil.ToCamelCase(name);
}
public static string MakeUnique(this string name, Func<string, bool> exists)
{
string uniqueName = name;
int count = 1;
while (exists(uniqueName))
uniqueName = string.Concat(name, count++);
return uniqueName;
}
public static bool IsKeyword(this string text, CodeLanguage language = CodeLanguage.CSharp)
{
return language == CodeLanguage.VisualBasic
? _visualBasicKeywords.Contains(text)
: _csharpKeywords.Contains(text);
}
public static string ToSafeName(this string name, CodeLanguage language = CodeLanguage.CSharp)
{
if (!name.IsKeyword(language))
return name;
return language == CodeLanguage.VisualBasic
? string.Format("[{0}]", name)
: "@" + name;
}
public static string ToType(this Type type, CodeLanguage language = CodeLanguage.CSharp)
{
return ToType(type.FullName, language);
}
public static string ToType(this string type, CodeLanguage language = CodeLanguage.CSharp)
{
if (type == "System.Xml.XmlDocument")
type = "System.String";
string t;
if (language == CodeLanguage.CSharp && _csharpTypeAlias.TryGetValue(type, out t))
return t;
return type;
}
public static string ToNullableType(this Type type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{
return ToNullableType(type.FullName, isNullable, language);
}
public static string ToNullableType(this string type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{
bool isValueType = type.IsValueType();
type = type.ToType(language);
if (!isValueType || !isNullable)
return type;
return language == CodeLanguage.VisualBasic
? string.Format("Nullable(Of {0})", type)
: type + "?";
}
public static bool IsValueType(this string type)
{
if (!type.StartsWith("System."))
return false;
var t = Type.GetType(type, false);
return t != null && t.IsValueType;
}
public static string ToDelimitedString(this IEnumerable<string> values, string delimiter, string format = null)
{
var sb = new StringBuilder();
foreach (var i in values)
{
if (sb.Length > 0)
sb.Append(delimiter);
if (string.IsNullOrEmpty(format))
sb.Append(i);
else
sb.AppendFormat(format, i);
}
return sb.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeSmith.Engine;
namespace SchemaMapper
{
public enum CodeLanguage
{
CSharp,
VisualBasic
}
public static class Extensions
{
private static readonly HashSet<string> _csharpKeywords;
private static readonly HashSet<string> _visualBasicKeywords;
private static readonly Dictionary<string, string> _csharpTypeAlias;
static Extensions()
{
_csharpKeywords = new HashSet<string>(StringComparer.Ordinal)
{
"as", "do", "if", "in", "is",
"for", "int", "new", "out", "ref", "try",
"base", "bool", "byte", "case", "char", "else", "enum", "goto", "lock", "long", "null", "this", "true", "uint", "void",
"break", "catch", "class", "const", "event", "false", "fixed", "float", "sbyte", "short", "throw", "ulong", "using", "while",
"double", "extern", "object", "params", "public", "return", "sealed", "sizeof", "static", "string", "struct", "switch", "typeof", "unsafe", "ushort",
"checked", "decimal", "default", "finally", "foreach", "private", "virtual",
"abstract", "continue", "delegate", "explicit", "implicit", "internal", "operator", "override", "readonly", "volatile",
"__arglist", "__makeref", "__reftype", "interface", "namespace", "protected", "unchecked",
"__refvalue", "stackalloc"
};
_visualBasicKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"as", "do", "if", "in", "is", "me", "of", "on", "or", "to",
"and", "dim", "end", "for", "get", "let", "lib", "mod", "new", "not", "rem", "set", "sub", "try", "xor",
"ansi", "auto", "byte", "call", "case", "cdbl", "cdec", "char", "cint", "clng", "cobj", "csng", "cstr", "date", "each", "else",
"enum", "exit", "goto", "like", "long", "loop", "next", "step", "stop", "then", "true", "wend", "when", "with",
"alias", "byref", "byval", "catch", "cbool", "cbyte", "cchar", "cdate", "class", "const", "ctype", "cuint", "culng", "endif", "erase", "error",
"event", "false", "gosub", "isnot", "redim", "sbyte", "short", "throw", "ulong", "until", "using", "while",
"csbyte", "cshort", "double", "elseif", "friend", "global", "module", "mybase", "object", "option", "orelse", "public", "resume", "return", "select", "shared",
"single", "static", "string", "typeof", "ushort",
"andalso", "boolean", "cushort", "decimal", "declare", "default", "finally", "gettype", "handles", "imports", "integer", "myclass", "nothing", "partial", "private", "shadows",
"trycast", "unicode", "variant",
"assembly", "continue", "delegate", "function", "inherits", "operator", "optional", "preserve", "property", "readonly", "synclock", "uinteger", "widening",
"addressof", "interface", "namespace", "narrowing", "overloads", "overrides", "protected", "structure", "writeonly",
"addhandler", "directcast", "implements", "paramarray", "raiseevent", "withevents",
"mustinherit", "overridable",
"mustoverride",
"removehandler",
"class_finalize", "notinheritable", "notoverridable",
"class_initialize"
};
_csharpTypeAlias = new Dictionary<string, string>(16)
{
{"System.Int16", "short"},
{"System.Int32", "int"},
{"System.Int64", "long"},
{"System.String", "string"},
{"System.Object", "object"},
{"System.Boolean", "bool"},
{"System.Void", "void"},
{"System.Char", "char"},
{"System.Byte", "byte"},
{"System.UInt16", "ushort"},
{"System.UInt32", "uint"},
{"System.UInt64", "ulong"},
{"System.SByte", "sbyte"},
{"System.Single", "float"},
{"System.Double", "double"},
{"System.Decimal", "decimal"}
};
}
public static string ToCamelCase(this string name)
{
return StringUtil.ToCamelCase(name);
}
public static string ToPascalCase(this string name)
{
return StringUtil.ToPascalCase(name);
}
public static string ToFieldName(this string name)
{
return "_" + StringUtil.ToCamelCase(name);
}
public static string MakeUnique(this string name, Func<string, bool> exists)
{
string uniqueName = name;
int count = 1;
while (exists(uniqueName))
uniqueName = string.Concat(name, count++);
return uniqueName;
}
public static bool IsKeyword(this string text, CodeLanguage language = CodeLanguage.CSharp)
{
return language == CodeLanguage.VisualBasic
? _visualBasicKeywords.Contains(text)
: _csharpKeywords.Contains(text);
}
public static string ToSafeName(this string name, CodeLanguage language = CodeLanguage.CSharp)
{
if (!name.IsKeyword(language))
return name;
return language == CodeLanguage.VisualBasic
? string.Format("[{0}]", name)
: "@" + name;
}
public static string ToType(this Type type, CodeLanguage language = CodeLanguage.CSharp)
{
return ToType(type.FullName, language);
}
public static string ToType(this string type, CodeLanguage language = CodeLanguage.CSharp)
{
if (type == "System.Xml.XmlDocument")
type = "System.String";
string t;
if (language == CodeLanguage.CSharp && _csharpTypeAlias.TryGetValue(type, out t))
return t;
return type;
}
public static string ToNullableType(this Type type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{
return ToNullableType(type.FullName, isNullable, language);
}
public static string ToNullableType(this string type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{
bool isValueType = type.IsValueType();
type = type.ToType(language);
if (!isValueType || !isNullable)
return type;
return language == CodeLanguage.VisualBasic
? string.Format("Nullable(Of {0})", type)
: type + "?";
}
public static bool IsValueType(this string type)
{
if (!type.StartsWith("System."))
return false;
var t = Type.GetType(type, false);
return t != null && t.IsValueType;
}
public static string ToDelimitedString(this IEnumerable<string> values, string delimiter, string format = null)
{
var sb = new StringBuilder();
foreach (var i in values)
{
if (sb.Length > 0)
sb.Append(delimiter);
if (string.IsNullOrEmpty(format))
sb.Append(i);
else
sb.AppendFormat(format, i);
}
return sb.ToString();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,294 +1,294 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity" Type="SchemaMapper.Entity" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace <%= MappingNamespace %>
{
public partial class <%= Entity.MappingName.ToSafeName() %>
: System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<<%= EntityNamespace %>.<%= Entity.ClassName.ToSafeName() %>>
{
public <%= Entity.MappingName.ToSafeName() %>()
{
// table
<% if (string.IsNullOrEmpty(Entity.TableSchema)) { %>
ToTable("<%= Entity.TableName %>");
<% } else { %>
ToTable("<%= Entity.TableName %>", "<%= Entity.TableSchema %>");
<% } %>
// keys
<% if (Entity.Properties.PrimaryKeys.Count() > 0) { %>
HasKey(t => <%= KeyExpression(Entity.Properties.PrimaryKeys, "t") %>);
<% } %>
// Properties
<%
foreach(var p in Entity.Properties)
{
Response.Write(PropertyExpression(p));
}
%>
// Relationships
<%
foreach(var r in Entity.Relationships.Where(e => e.IsMapped))
{
if (r.IsManyToMany)
Response.Write(ManyToManyExpression(r));
else
Response.Write(RelationshipExpression(r));
}
%>
}
}
}
<script runat="template">
public string PropertyExpression(Property property)
{
bool isString = property.SystemType == typeof(string);
bool isByteArray = property.SystemType == typeof(byte[]);
bool isDecimal = property.SystemType == typeof(Decimal);
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("Property(t => t.");
sb.Append(property.PropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasColumnName(\"");
sb.Append(property.ColumnName);
sb.Append("\")");
if (property.IsIdentity == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
}
else if (property.IsAutoGenerated == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)");
}
if ((isString || isByteArray) && (property.MaxLength > 0 && property.MaxLength < 8000))
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasMaxLength(");
sb.Append(property.MaxLength);
sb.Append(")");
}
if (isDecimal && property.Precision.HasValue && property.Scale.HasValue)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasPrecision(");
sb.Append(property.Precision);
sb.Append(", ");
sb.Append(property.Scale);
sb.Append(")");
}
if (property.IsRowVersion == true && isByteArray)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".IsRowVersion()");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
if (property.IsRequired == true)
sb.Append(".IsRequired()");
else
sb.Append(".IsOptional()");
sb.AppendLine(";");
return sb.ToString();
}
public string ManyToManyExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("HasMany(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".Map(m =>");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("{");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.ToTable(\"");
sb.Append(relationship.JoinTable);
sb.Append("\", \"");
sb.Append(relationship.JoinSchema);
sb.Append("\");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapLeftKey(");
sb.Append(relationship.JoinThisColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapRightKey(");
sb.Append(relationship.JoinOtherColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("})");
sb.Append(";");
sb.AppendLine();
return sb.ToString();
}
public string RelationshipExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
if (relationship.ThisCardinality == Cardinality.One)
{
sb.Append("HasRequired(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
else if (relationship.ThisCardinality == Cardinality.ZeroOrOne)
{
sb.Append("HasOptional(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
if (relationship.OtherCardinality == Cardinality.Many)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasForeignKey(d => ");
sb.Append(KeyExpression(relationship.ThisProperties, "d"));
sb.Append(")");
}
else
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithOptional(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WillCascadeOnDelete(");
sb.Append(relationship.CascadeDelete == true ? "true" : "false");
sb.Append(")");
sb.AppendLine(";");
return sb.ToString();
}
public string KeyExpression(IEnumerable<Property> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault().PropertyName);
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p.PropertyName);
}
sb.Append(" }");
}
return sb.ToString();
}
public string KeyExpression(IEnumerable<string> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault());
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p);
}
sb.Append(" }");
}
return sb.ToString();
}
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity" Type="SchemaMapper.Entity" %>
<%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %>
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace <%= MappingNamespace %>
{
public partial class <%= Entity.MappingName.ToSafeName() %>
: System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<<%= EntityNamespace %>.<%= Entity.ClassName.ToSafeName() %>>
{
public <%= Entity.MappingName.ToSafeName() %>()
{
// table
<% if (string.IsNullOrEmpty(Entity.TableSchema)) { %>
ToTable("<%= Entity.TableName %>");
<% } else { %>
ToTable("<%= Entity.TableName %>", "<%= Entity.TableSchema %>");
<% } %>
// keys
<% if (Entity.Properties.PrimaryKeys.Count() > 0) { %>
HasKey(t => <%= KeyExpression(Entity.Properties.PrimaryKeys, "t") %>);
<% } %>
// Properties
<%
foreach(var p in Entity.Properties)
{
Response.Write(PropertyExpression(p));
}
%>
// Relationships
<%
foreach(var r in Entity.Relationships.Where(e => e.IsMapped))
{
if (r.IsManyToMany)
Response.Write(ManyToManyExpression(r));
else
Response.Write(RelationshipExpression(r));
}
%>
}
}
}
<script runat="template">
public string PropertyExpression(Property property)
{
bool isString = property.SystemType == typeof(string);
bool isByteArray = property.SystemType == typeof(byte[]);
bool isDecimal = property.SystemType == typeof(Decimal);
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("Property(t => t.");
sb.Append(property.PropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasColumnName(\"");
sb.Append(property.ColumnName);
sb.Append("\")");
if (property.IsIdentity == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
}
else if (property.IsAutoGenerated == true)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)");
}
if ((isString || isByteArray) && (property.MaxLength > 0 && property.MaxLength < 8000))
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasMaxLength(");
sb.Append(property.MaxLength);
sb.Append(")");
}
if (isDecimal && property.Precision.HasValue && property.Scale.HasValue)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasPrecision(");
sb.Append(property.Precision);
sb.Append(", ");
sb.Append(property.Scale);
sb.Append(")");
}
if (property.IsRowVersion == true && isByteArray)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".IsRowVersion()");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
if (property.IsRequired == true)
sb.Append(".IsRequired()");
else
sb.Append(".IsOptional()");
sb.AppendLine(";");
return sb.ToString();
}
public string ManyToManyExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
sb.Append("HasMany(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".Map(m =>");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("{");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.ToTable(\"");
sb.Append(relationship.JoinTable);
sb.Append("\", \"");
sb.Append(relationship.JoinSchema);
sb.Append("\");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapLeftKey(");
sb.Append(relationship.JoinThisColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 5 * 4);
sb.Append("m.MapRightKey(");
sb.Append(relationship.JoinOtherColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append("})");
sb.Append(";");
sb.AppendLine();
return sb.ToString();
}
public string RelationshipExpression(Relationship relationship)
{
StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4);
if (relationship.ThisCardinality == Cardinality.One)
{
sb.Append("HasRequired(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
else if (relationship.ThisCardinality == Cardinality.ZeroOrOne)
{
sb.Append("HasOptional(t => t.");
sb.Append(relationship.ThisPropertyName);
sb.Append(")");
}
if (relationship.OtherCardinality == Cardinality.Many)
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".HasForeignKey(d => ");
sb.Append(KeyExpression(relationship.ThisProperties, "d"));
sb.Append(")");
}
else
{
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WithOptional(t => t.");
sb.Append(relationship.OtherPropertyName);
sb.Append(")");
}
sb.AppendLine();
sb.Append(' ', 4 * 4);
sb.Append(".WillCascadeOnDelete(");
sb.Append(relationship.CascadeDelete == true ? "true" : "false");
sb.Append(")");
sb.AppendLine(";");
return sb.ToString();
}
public string KeyExpression(IEnumerable<Property> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault().PropertyName);
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p.PropertyName);
}
sb.Append(" }");
}
return sb.ToString();
}
public string KeyExpression(IEnumerable<string> keys, string alias = "t")
{
StringBuilder sb = new StringBuilder();
if (keys.Count() == 1)
{
sb.Append(alias);
sb.Append(".");
sb.Append(keys.FirstOrDefault());
}
else
{
sb.Append("new { ");
foreach(var p in keys)
{
if (sb.Length > 6)
sb.Append(", ");
sb.Append(alias);
sb.Append(".");
sb.Append(p);
}
sb.Append(" }");
}
return sb.ToString();
}
</script>

View File

@@ -1,370 +1,370 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml.Serialization;
namespace SchemaMapper
{
#region Base
public enum Cardinality
{
ZeroOrOne,
One,
Many
}
public class EntityBase
{
[XmlIgnore]
public bool IsProcessed { get; set; }
}
#endregion
#region Model
[DebuggerDisplay("Context: {ContextName}, Database: {DatabaseName}")]
public class EntityContext : EntityBase
{
public EntityContext()
{
Entities = new EntityCollection();
}
public string ClassName { get; set; }
public string DatabaseName { get; set; }
public EntityCollection Entities { get; set; }
public void RenameEntity(string originalName, string newName)
{
if (originalName == newName)
return;
Debug.WriteLine("Rename Entity '{0}' to '{1}'.", originalName, newName);
foreach (var entity in Entities)
{
if (entity.ClassName == originalName)
entity.ClassName = newName;
foreach (var relationship in entity.Relationships)
{
if (relationship.ThisEntity == originalName)
relationship.ThisEntity = newName;
if (relationship.OtherEntity == originalName)
relationship.OtherEntity = newName;
}
}
}
public void RenameProperty(string entityName, string originalName, string newName)
{
if (originalName == newName)
return;
Debug.WriteLine("Rename Property '{0}' to '{1}' in Entity '{2}'.", originalName, newName, entityName);
foreach (var entity in Entities)
{
if (entity.ClassName == entityName)
{
var property = entity.Properties.ByProperty(originalName);
if (property != null)
property.PropertyName = newName;
}
foreach (var relationship in entity.Relationships)
{
if (relationship.ThisEntity == entityName)
for (int i = 0; i < relationship.ThisProperties.Count; i++)
if (relationship.ThisProperties[i] == originalName)
relationship.ThisProperties[i] = newName;
if (relationship.OtherEntity == entityName)
for (int i = 0; i < relationship.OtherProperties.Count; i++)
if (relationship.OtherProperties[i] == originalName)
relationship.OtherProperties[i] = newName;
}
}
}
}
[DebuggerDisplay("Class: {ClassName}, Table: {FullName}, Context: {ContextName}")]
public class Entity : EntityBase
{
public Entity()
{
Properties = new PropertyCollection();
Relationships = new RelationshipCollection();
Methods = new MethodCollection();
}
public string ContextName { get; set; }
public string ClassName { get; set; }
public string MappingName { get; set; }
public string Description{ get;set;}
public string TableSchema { get; set; }
public string TableName { get; set; }
public string FullName { get; set; }
public PropertyCollection Properties { get; set; }
public RelationshipCollection Relationships { get; set; }
public MethodCollection Methods { get; set; }
}
[DebuggerDisplay("Property: {PropertyName}, Column: {ColumnName}, Type: {NativeType}")]
public class Property : EntityBase
{
public string PropertyName { get; set; }
public string ColumnName { get; set; }
public string Description { get; set; }
public DbType DataType { get; set; }
public string NativeType { get; set; }
[XmlIgnore]
public Type SystemType { get; set; }
public int? Order { get; set; }
public bool OrderSpecified
{
get { return Order.HasValue; }
}
public bool? IsNullable { get; set; }
public bool IsNullableSpecified
{
get { return IsNullable.HasValue; }
}
public bool IsRequired
{
get { return IsNullable == false; }
set { IsNullable = !value; }
}
public bool IsOptional
{
get { return IsNullable == true; }
set { IsNullable = value; }
}
public bool? IsPrimaryKey { get; set; }
public bool IsPrimaryKeySpecified
{
get { return IsPrimaryKey.HasValue; }
}
public bool? IsForeignKey { get; set; }
public bool IsForeignKeySpecified
{
get { return IsForeignKey.HasValue; }
}
public bool? IsAutoGenerated { get; set; }
public bool IsAutoGeneratedSpecified
{
get { return IsAutoGenerated.HasValue; }
}
public bool? IsReadOnly { get; set; }
public bool IsReadOnlySpecified
{
get { return IsReadOnly.HasValue; }
}
public bool? IsRowVersion { get; set; }
public bool IsRowVersionSpecified
{
get { return IsRowVersion.HasValue; }
}
public bool? IsIdentity { get; set; }
public bool IsIdentitySpecified
{
get { return IsIdentity.HasValue; }
}
public bool? IsUnique { get; set; }
public bool IsUniqueSpecified
{
get { return IsUnique.HasValue; }
}
public bool? IsUnicode { get; set; }
public bool IsUnicodeSpecified
{
get { return IsUnicode.HasValue; }
}
public bool? IsFixedLength { get; set; }
public bool IsFixedLengthSpecified
{
get { return IsFixedLength.HasValue; }
}
public int? MaxLength { get; set; }
public bool MaxLengthSpecified
{
get { return MaxLength.HasValue; }
}
public byte? Precision { get; set; }
public bool PrecisionSpecified
{
get { return Precision.HasValue; }
}
public int? Scale { get; set; }
public bool ScaleSpecified
{
get { return Scale.HasValue; }
}
}
[DebuggerDisplay("Other: {OtherEntity}, Property: {OtherPropertyName}, Relationship: {RelationshipName}")]
public class Relationship : EntityBase
{
public Relationship()
{
OtherProperties = new List<string>();
ThisProperties = new List<string>();
}
public string RelationshipName { get; set; }
public string ThisEntity { get; set; }
public string ThisPropertyName { get; set; }
public Cardinality ThisCardinality { get; set; }
public List<string> ThisProperties { get; set; }
public string OtherEntity { get; set; }
public string OtherPropertyName { get; set; }
public Cardinality OtherCardinality { get; set; }
public List<string> OtherProperties { get; set; }
public bool? CascadeDelete { get; set; }
public bool IsForeignKey { get; set; }
public bool IsMapped { get; set; }
public bool IsManyToMany
{
get
{
return ThisCardinality == Cardinality.Many
&& OtherCardinality == Cardinality.Many;
}
}
public bool IsOneToOne
{
get
{
return ThisCardinality != Cardinality.Many
&& OtherCardinality != Cardinality.Many;
}
}
public string JoinTable { get; set; }
public string JoinSchema { get; set; }
public List<string> JoinThisColumn { get; set; }
public List<string> JoinOtherColumn { get; set; }
}
[DebuggerDisplay("Suffix: {NameSuffix}, IsKey: {IsKey}, IsUnique: {IsUnique}")]
public class Method : EntityBase
{
public Method()
{
Properties = new List<Property>();
}
public string NameSuffix { get; set; }
public string SourceName { get; set; }
public bool IsKey { get; set; }
public bool IsUnique { get; set; }
public bool IsIndex { get; set; }
public List<Property> Properties { get; set; }
}
#endregion
#region Collections
public class EntityCollection
: ObservableCollection<Entity>
{
public bool IsProcessed { get; set; }
public Entity ByTable(string fullName)
{
return this.FirstOrDefault(x => x.FullName == fullName);
}
public Entity ByTable(string tableName, string tableSchema)
{
return this.FirstOrDefault(x => x.TableName == tableName && x.TableSchema == tableSchema);
}
public Entity ByClass(string className)
{
return this.FirstOrDefault(x => x.ClassName == className);
}
public Entity ByContext(string contextName)
{
return this.FirstOrDefault(x => x.ContextName == contextName);
}
}
public class PropertyCollection
: ObservableCollection<Property>
{
public bool IsProcessed { get; set; }
public IEnumerable<Property> PrimaryKeys
{
get { return this.Where(p => p.IsPrimaryKey == true); }
}
public IEnumerable<Property> ForeignKeys
{
get { return this.Where(p => p.IsForeignKey == true); }
}
public Property ByColumn(string columnName)
{
return this.FirstOrDefault(x => x.ColumnName == columnName);
}
public Property ByProperty(string propertyName)
{
return this.FirstOrDefault(x => x.PropertyName == propertyName);
}
}
public class RelationshipCollection
: ObservableCollection<Relationship>
{
public bool IsProcessed { get; set; }
public Relationship ByName(string name)
{
return this.FirstOrDefault(x => x.RelationshipName == name);
}
public Relationship ByProperty(string propertyName)
{
return this.FirstOrDefault(x => x.ThisPropertyName == propertyName);
}
public Relationship ByOther(string name)
{
return this.FirstOrDefault(x => x.OtherEntity == name);
}
}
public class MethodCollection
: ObservableCollection<Method>
{
public bool IsProcessed { get; set; }
}
#endregion
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml.Serialization;
namespace SchemaMapper
{
#region Base
public enum Cardinality
{
ZeroOrOne,
One,
Many
}
public class EntityBase
{
[XmlIgnore]
public bool IsProcessed { get; set; }
}
#endregion
#region Model
[DebuggerDisplay("Context: {ContextName}, Database: {DatabaseName}")]
public class EntityContext : EntityBase
{
public EntityContext()
{
Entities = new EntityCollection();
}
public string ClassName { get; set; }
public string DatabaseName { get; set; }
public EntityCollection Entities { get; set; }
public void RenameEntity(string originalName, string newName)
{
if (originalName == newName)
return;
Debug.WriteLine("Rename Entity '{0}' to '{1}'.", originalName, newName);
foreach (var entity in Entities)
{
if (entity.ClassName == originalName)
entity.ClassName = newName;
foreach (var relationship in entity.Relationships)
{
if (relationship.ThisEntity == originalName)
relationship.ThisEntity = newName;
if (relationship.OtherEntity == originalName)
relationship.OtherEntity = newName;
}
}
}
public void RenameProperty(string entityName, string originalName, string newName)
{
if (originalName == newName)
return;
Debug.WriteLine("Rename Property '{0}' to '{1}' in Entity '{2}'.", originalName, newName, entityName);
foreach (var entity in Entities)
{
if (entity.ClassName == entityName)
{
var property = entity.Properties.ByProperty(originalName);
if (property != null)
property.PropertyName = newName;
}
foreach (var relationship in entity.Relationships)
{
if (relationship.ThisEntity == entityName)
for (int i = 0; i < relationship.ThisProperties.Count; i++)
if (relationship.ThisProperties[i] == originalName)
relationship.ThisProperties[i] = newName;
if (relationship.OtherEntity == entityName)
for (int i = 0; i < relationship.OtherProperties.Count; i++)
if (relationship.OtherProperties[i] == originalName)
relationship.OtherProperties[i] = newName;
}
}
}
}
[DebuggerDisplay("Class: {ClassName}, Table: {FullName}, Context: {ContextName}")]
public class Entity : EntityBase
{
public Entity()
{
Properties = new PropertyCollection();
Relationships = new RelationshipCollection();
Methods = new MethodCollection();
}
public string ContextName { get; set; }
public string ClassName { get; set; }
public string MappingName { get; set; }
public string Description{ get;set;}
public string TableSchema { get; set; }
public string TableName { get; set; }
public string FullName { get; set; }
public PropertyCollection Properties { get; set; }
public RelationshipCollection Relationships { get; set; }
public MethodCollection Methods { get; set; }
}
[DebuggerDisplay("Property: {PropertyName}, Column: {ColumnName}, Type: {NativeType}")]
public class Property : EntityBase
{
public string PropertyName { get; set; }
public string ColumnName { get; set; }
public string Description { get; set; }
public DbType DataType { get; set; }
public string NativeType { get; set; }
[XmlIgnore]
public Type SystemType { get; set; }
public int? Order { get; set; }
public bool OrderSpecified
{
get { return Order.HasValue; }
}
public bool? IsNullable { get; set; }
public bool IsNullableSpecified
{
get { return IsNullable.HasValue; }
}
public bool IsRequired
{
get { return IsNullable == false; }
set { IsNullable = !value; }
}
public bool IsOptional
{
get { return IsNullable == true; }
set { IsNullable = value; }
}
public bool? IsPrimaryKey { get; set; }
public bool IsPrimaryKeySpecified
{
get { return IsPrimaryKey.HasValue; }
}
public bool? IsForeignKey { get; set; }
public bool IsForeignKeySpecified
{
get { return IsForeignKey.HasValue; }
}
public bool? IsAutoGenerated { get; set; }
public bool IsAutoGeneratedSpecified
{
get { return IsAutoGenerated.HasValue; }
}
public bool? IsReadOnly { get; set; }
public bool IsReadOnlySpecified
{
get { return IsReadOnly.HasValue; }
}
public bool? IsRowVersion { get; set; }
public bool IsRowVersionSpecified
{
get { return IsRowVersion.HasValue; }
}
public bool? IsIdentity { get; set; }
public bool IsIdentitySpecified
{
get { return IsIdentity.HasValue; }
}
public bool? IsUnique { get; set; }
public bool IsUniqueSpecified
{
get { return IsUnique.HasValue; }
}
public bool? IsUnicode { get; set; }
public bool IsUnicodeSpecified
{
get { return IsUnicode.HasValue; }
}
public bool? IsFixedLength { get; set; }
public bool IsFixedLengthSpecified
{
get { return IsFixedLength.HasValue; }
}
public int? MaxLength { get; set; }
public bool MaxLengthSpecified
{
get { return MaxLength.HasValue; }
}
public byte? Precision { get; set; }
public bool PrecisionSpecified
{
get { return Precision.HasValue; }
}
public int? Scale { get; set; }
public bool ScaleSpecified
{
get { return Scale.HasValue; }
}
}
[DebuggerDisplay("Other: {OtherEntity}, Property: {OtherPropertyName}, Relationship: {RelationshipName}")]
public class Relationship : EntityBase
{
public Relationship()
{
OtherProperties = new List<string>();
ThisProperties = new List<string>();
}
public string RelationshipName { get; set; }
public string ThisEntity { get; set; }
public string ThisPropertyName { get; set; }
public Cardinality ThisCardinality { get; set; }
public List<string> ThisProperties { get; set; }
public string OtherEntity { get; set; }
public string OtherPropertyName { get; set; }
public Cardinality OtherCardinality { get; set; }
public List<string> OtherProperties { get; set; }
public bool? CascadeDelete { get; set; }
public bool IsForeignKey { get; set; }
public bool IsMapped { get; set; }
public bool IsManyToMany
{
get
{
return ThisCardinality == Cardinality.Many
&& OtherCardinality == Cardinality.Many;
}
}
public bool IsOneToOne
{
get
{
return ThisCardinality != Cardinality.Many
&& OtherCardinality != Cardinality.Many;
}
}
public string JoinTable { get; set; }
public string JoinSchema { get; set; }
public List<string> JoinThisColumn { get; set; }
public List<string> JoinOtherColumn { get; set; }
}
[DebuggerDisplay("Suffix: {NameSuffix}, IsKey: {IsKey}, IsUnique: {IsUnique}")]
public class Method : EntityBase
{
public Method()
{
Properties = new List<Property>();
}
public string NameSuffix { get; set; }
public string SourceName { get; set; }
public bool IsKey { get; set; }
public bool IsUnique { get; set; }
public bool IsIndex { get; set; }
public List<Property> Properties { get; set; }
}
#endregion
#region Collections
public class EntityCollection
: ObservableCollection<Entity>
{
public bool IsProcessed { get; set; }
public Entity ByTable(string fullName)
{
return this.FirstOrDefault(x => x.FullName == fullName);
}
public Entity ByTable(string tableName, string tableSchema)
{
return this.FirstOrDefault(x => x.TableName == tableName && x.TableSchema == tableSchema);
}
public Entity ByClass(string className)
{
return this.FirstOrDefault(x => x.ClassName == className);
}
public Entity ByContext(string contextName)
{
return this.FirstOrDefault(x => x.ContextName == contextName);
}
}
public class PropertyCollection
: ObservableCollection<Property>
{
public bool IsProcessed { get; set; }
public IEnumerable<Property> PrimaryKeys
{
get { return this.Where(p => p.IsPrimaryKey == true); }
}
public IEnumerable<Property> ForeignKeys
{
get { return this.Where(p => p.IsForeignKey == true); }
}
public Property ByColumn(string columnName)
{
return this.FirstOrDefault(x => x.ColumnName == columnName);
}
public Property ByProperty(string propertyName)
{
return this.FirstOrDefault(x => x.PropertyName == propertyName);
}
}
public class RelationshipCollection
: ObservableCollection<Relationship>
{
public bool IsProcessed { get; set; }
public Relationship ByName(string name)
{
return this.FirstOrDefault(x => x.RelationshipName == name);
}
public Relationship ByProperty(string propertyName)
{
return this.FirstOrDefault(x => x.ThisPropertyName == propertyName);
}
public Relationship ByOther(string name)
{
return this.FirstOrDefault(x => x.OtherEntity == name);
}
}
public class MethodCollection
: ObservableCollection<Method>
{
public bool IsProcessed { get; set; }
}
#endregion
}

File diff suppressed because it is too large Load Diff