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,309 +1,309 @@
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %> <%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %> <%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Assembly Name="Mono.Cecil" Path="..\Common" %> <%@ Assembly Name="Mono.Cecil" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %> <%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %> <%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %>
<%@ Assembly Src="Internal\Model.cs" %> <%@ Assembly Src="Internal\Model.cs" %>
<%@ Assembly Src="Internal\Extensions.cs" %> <%@ Assembly Src="Internal\Extensions.cs" %>
<%@ Assembly Src="Internal\Generator.cs" %> <%@ Assembly Src="Internal\Generator.cs" %>
<%@ Assembly Src="Internal\Parser.cs" %> <%@ Assembly Src="Internal\Parser.cs" %>
<%@ Import Namespace="System.Collections.Generic" %> <%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Linq" %> <%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %> <%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %> <%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %> <%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="SourceDatabase" <%@ Property Name="SourceDatabase"
Type="SchemaExplorer.DatabaseSchema" Type="SchemaExplorer.DatabaseSchema"
Category="1.Database" Category="1.Database"
OnChanged="OnSourceDatabaseChanged" OnChanged="OnSourceDatabaseChanged"
Description="The source database." %> Description="The source database." %>
<%@ Property Name="ContextNamespace" <%@ Property Name="ContextNamespace"
Type="System.String" Type="System.String"
Category="2.Class" Category="2.Class"
OnChanged="OnContextNamespaceChanged" OnChanged="OnContextNamespaceChanged"
Description="The namespace to use for the data context class files."%> Description="The namespace to use for the data context class files."%>
<%@ Property Name="EntityNamespace" <%@ Property Name="EntityNamespace"
Type="System.String" Type="System.String"
Category="2.Class" Category="2.Class"
Description="The namespace to use for the entity class files."%> Description="The namespace to use for the entity class files."%>
<%@ Property Name="MappingNamespace" <%@ Property Name="MappingNamespace"
Type="System.String" Type="System.String"
Category="2.Class" Category="2.Class"
Description="The namespace to use for the mapping class files."%> Description="The namespace to use for the mapping class files."%>
<%@ Property Name="ContextDirectory" <%@ Property Name="ContextDirectory"
Category="3.Output" Category="3.Output"
Type="System.String" Type="System.String"
Default=".\" Default=".\"
Optional="True" Optional="True"
Description="The folder to save the generated context files." Description="The folder to save the generated context files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %> Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="EntityDirectory" <%@ Property Name="EntityDirectory"
Category="3.Output" Category="3.Output"
Type="System.String" Type="System.String"
Default=".\Entities" Default=".\Entities"
Optional="True" Optional="True"
Description="The folder to save the generated entity files." Description="The folder to save the generated entity files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %> Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="MappingDirectory" <%@ Property Name="MappingDirectory"
Category="3.Output" Category="3.Output"
Type="System.String" Type="System.String"
Default=".\Mapping" Default=".\Mapping"
Optional="True" Optional="True"
Description="The folder to save the generated mapping files." Description="The folder to save the generated mapping files."
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %> Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="TableNaming" <%@ Property Name="TableNaming"
Type="SchemaMapper.TableNaming" Type="SchemaMapper.TableNaming"
Category="4.Hints" Category="4.Hints"
Default="Singular" Default="Singular"
Description="Provide generator a hint as to how the tables are named." %> Description="Provide generator a hint as to how the tables are named." %>
<%@ Property Name="EntityNaming" <%@ Property Name="EntityNaming"
Type="SchemaMapper.EntityNaming" Type="SchemaMapper.EntityNaming"
Category="4.Hints" Category="4.Hints"
Default="Singular" Default="Singular"
Description="Tell generator how the entities are to be named." %> Description="Tell generator how the entities are to be named." %>
<%@ Property Name="RelationshipNaming" <%@ Property Name="RelationshipNaming"
Type="SchemaMapper.RelationshipNaming" Type="SchemaMapper.RelationshipNaming"
Category="4.Hints" Category="4.Hints"
Default="Plural" Default="Plural"
Description="Tell generator how the relationships are to be named." %> Description="Tell generator how the relationships are to be named." %>
<%@ Property Name="ContextNaming" <%@ Property Name="ContextNaming"
Type="SchemaMapper.ContextNaming" Type="SchemaMapper.ContextNaming"
Category="4.Hints" Category="4.Hints"
Default="Plural" Default="Plural"
Description="Tell generator how the context properties are to be named." %> Description="Tell generator how the context properties are to be named." %>
<%@ Property Name="IgnoreList" <%@ Property Name="IgnoreList"
Type="CodeSmith.CustomProperties.StringCollection" Type="CodeSmith.CustomProperties.StringCollection"
Category="5.Customization" Category="5.Customization"
Default="sysdiagrams$" Default="sysdiagrams$"
Optional="True" Optional="True"
Description="List of regular expressions to ignore tables, views and commands when generating mapping." %> Description="List of regular expressions to ignore tables, views and commands when generating mapping." %>
<%@ Property Name="InclusionMode" <%@ Property Name="InclusionMode"
Type="Boolean" Type="Boolean"
Category="5.Customization" Category="5.Customization"
Default="False" Default="False"
Optional="True" Optional="True"
Description="Change the IgnoreList to be a list of table to include instead of ignore." %> Description="Change the IgnoreList to be a list of table to include instead of ignore." %>
<%@ Property Name="CleanExpressions" <%@ Property Name="CleanExpressions"
Type="CodeSmith.CustomProperties.StringCollection" Type="CodeSmith.CustomProperties.StringCollection"
Category="5.Customization" Category="5.Customization"
Default="^(sp|tbl|udf|vw)_" Default="^(sp|tbl|udf|vw)_"
Optional="True" Optional="True"
Description="List of regular expressions to clean table, view and column names." %> Description="List of regular expressions to clean table, view and column names." %>
<%@ Property Name="InterfaceMode" <%@ Property Name="InterfaceMode"
Type="Boolean" Type="Boolean"
Category="5.Customization" Category="5.Customization"
Default="False" Default="False"
Optional="True" Optional="True"
Description="Use interfaces for DbContext." %> Description="Use interfaces for DbContext." %>
<%@ Register Name="ContextGeneratedClass" <%@ Register Name="ContextGeneratedClass"
Template="Internal\Context.Generated.cst" Template="Internal\Context.Generated.cst"
MergeProperties="False" %> MergeProperties="False" %>
<%@ Register Name="EntityGeneratedClass" <%@ Register Name="EntityGeneratedClass"
Template="Internal\Entity.Generated.cst" Template="Internal\Entity.Generated.cst"
MergeProperties="False" %> MergeProperties="False" %>
<%@ Register Name="MappingGeneratedClass" <%@ Register Name="MappingGeneratedClass"
Template="Internal\Mapping.Generated.cst" Template="Internal\Mapping.Generated.cst"
MergeProperties="False" %> MergeProperties="False" %>
Generating Entities ... Generating Entities ...
<% Generate(); %> <% Generate(); %>
<script runat="template"> <script runat="template">
public void Generate() public void Generate()
{ {
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
string outputDirectory = Path.GetFullPath(ContextDirectory); string outputDirectory = Path.GetFullPath(ContextDirectory);
if (!Directory.Exists(outputDirectory)) if (!Directory.Exists(outputDirectory))
Directory.CreateDirectory(outputDirectory); Directory.CreateDirectory(outputDirectory);
if (SourceDatabase != null) if (SourceDatabase != null)
{ {
this.Progress.MaximumValue = (SourceDatabase.Tables.Count * 3) + 1; this.Progress.MaximumValue = (SourceDatabase.Tables.Count * 3) + 1;
this.Progress.Step = 1; this.Progress.Step = 1;
} }
Generator generator = new Generator(); Generator generator = new Generator();
generator.Settings.TableNaming = TableNaming; generator.Settings.TableNaming = TableNaming;
generator.Settings.EntityNaming = EntityNaming; generator.Settings.EntityNaming = EntityNaming;
generator.Settings.RelationshipNaming = RelationshipNaming; generator.Settings.RelationshipNaming = RelationshipNaming;
generator.Settings.ContextNaming = ContextNaming; generator.Settings.ContextNaming = ContextNaming;
foreach(string s in IgnoreList) foreach(string s in IgnoreList)
if (!string.IsNullOrEmpty(s)) if (!string.IsNullOrEmpty(s))
generator.Settings.IgnoreExpressions.Add(s); generator.Settings.IgnoreExpressions.Add(s);
foreach(string s in CleanExpressions) foreach(string s in CleanExpressions)
if (!string.IsNullOrEmpty(s)) if (!string.IsNullOrEmpty(s))
generator.Settings.CleanExpressions.Add(s); generator.Settings.CleanExpressions.Add(s);
generator.SchemaItemProcessed += OnSchemaItemProcessed; generator.SchemaItemProcessed += OnSchemaItemProcessed;
// generate from database // generate from database
EntityContext context = generator.Generate(SourceDatabase); EntityContext context = generator.Generate(SourceDatabase);
// update model from source files // update model from source files
Synchronizer.UpdateFromSource(context, ContextDirectory, MappingDirectory); Synchronizer.UpdateFromSource(context, ContextDirectory, MappingDirectory);
CreateContextClass(context); CreateContextClass(context);
CreateMappingClasses(context); CreateMappingClasses(context);
CreateEntityClasses(context); CreateEntityClasses(context);
this.RegisterReference("System.Configuration"); this.RegisterReference("System.Configuration");
this.RegisterReference("System.Data"); this.RegisterReference("System.Data");
this.RegisterReference("System.Data.Entity"); this.RegisterReference("System.Data.Entity");
this.RegisterReference("System.Runtime.Serialization"); this.RegisterReference("System.Runtime.Serialization");
this.RegisterReference("EntityFramework"); this.RegisterReference("EntityFramework");
watch.Stop(); watch.Stop();
Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms"); Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms");
} }
public void CreateContextClass(EntityContext entityContext) public void CreateContextClass(EntityContext entityContext)
{ {
ContextGeneratedClass generatedClass = this.Create<ContextGeneratedClass>(); ContextGeneratedClass generatedClass = this.Create<ContextGeneratedClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
string rootDirectory = Path.GetFullPath(ContextDirectory); string rootDirectory = Path.GetFullPath(ContextDirectory);
string className = entityContext.ClassName; string className = entityContext.ClassName;
string generatedFile = className + ".cs"; string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile); generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.EntityContext = entityContext; generatedClass.EntityContext = entityContext;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
public void CreateMappingClasses(EntityContext entityContext) public void CreateMappingClasses(EntityContext entityContext)
{ {
MappingGeneratedClass generatedClass = this.Create<MappingGeneratedClass>(); MappingGeneratedClass generatedClass = this.Create<MappingGeneratedClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
foreach(Entity entity in entityContext.Entities) foreach(Entity entity in entityContext.Entities)
{ {
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
Debug.WriteLine(string.Format( Debug.WriteLine(string.Format(
"Creating Mapping Class '{0}' ...", "Creating Mapping Class '{0}' ...",
entity.ClassName)); entity.ClassName));
string rootDirectory = Path.GetFullPath(MappingDirectory); string rootDirectory = Path.GetFullPath(MappingDirectory);
CreateMapping(generatedClass, entity, rootDirectory); CreateMapping(generatedClass, entity, rootDirectory);
Debug.WriteLine(string.Format( Debug.WriteLine(string.Format(
"Created Mapping Class '{0}' in {1} ms.", "Created Mapping Class '{0}' in {1} ms.",
entity.ClassName, entity.ClassName,
watch.Elapsed.TotalMilliseconds.ToString())); watch.Elapsed.TotalMilliseconds.ToString()));
this.Progress.PerformStep(); this.Progress.PerformStep();
} }
} }
public void CreateMapping(MappingGeneratedClass generatedClass, Entity entity, string rootDirectory) public void CreateMapping(MappingGeneratedClass generatedClass, Entity entity, string rootDirectory)
{ {
string className = entity.MappingName; string className = entity.MappingName;
string generatedFile = className + ".cs"; string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile); generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.Entity = entity; generatedClass.Entity = entity;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
public void CreateEntityClasses(EntityContext entityContext) public void CreateEntityClasses(EntityContext entityContext)
{ {
EntityGeneratedClass generatedClass = this.Create<EntityGeneratedClass>(); EntityGeneratedClass generatedClass = this.Create<EntityGeneratedClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
foreach(Entity entity in entityContext.Entities) foreach(Entity entity in entityContext.Entities)
{ {
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
Debug.WriteLine(string.Format( Debug.WriteLine(string.Format(
"Creating Entity Class '{0}' ...", "Creating Entity Class '{0}' ...",
entity.ClassName)); entity.ClassName));
string rootDirectory = Path.GetFullPath(EntityDirectory); string rootDirectory = Path.GetFullPath(EntityDirectory);
CreateEntity(generatedClass, entity, rootDirectory); CreateEntity(generatedClass, entity, rootDirectory);
Debug.WriteLine(string.Format( Debug.WriteLine(string.Format(
"Created Entity Class '{0}' in {1} ms.", "Created Entity Class '{0}' in {1} ms.",
entity.ClassName, entity.ClassName,
watch.Elapsed.TotalMilliseconds.ToString())); watch.Elapsed.TotalMilliseconds.ToString()));
this.Progress.PerformStep(); this.Progress.PerformStep();
} }
} }
public void CreateEntity(EntityGeneratedClass generatedClass, Entity entity, string rootDirectory) public void CreateEntity(EntityGeneratedClass generatedClass, Entity entity, string rootDirectory)
{ {
string className = entity.ClassName; string className = entity.ClassName;
string generatedFile = className + ".cs"; string generatedFile = className + ".cs";
generatedFile = Path.Combine(rootDirectory, generatedFile); generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.Entity = entity; generatedClass.Entity = entity;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
private void OnSchemaItemProcessed(object sender, SchemaItemProcessedEventArgs e) private void OnSchemaItemProcessed(object sender, SchemaItemProcessedEventArgs e)
{ {
this.Progress.PerformStep(); this.Progress.PerformStep();
Response.WriteLine(e.Name); Response.WriteLine(e.Name);
} }
private void OnSourceDatabaseChanged(object sender, EventArgs e) private void OnSourceDatabaseChanged(object sender, EventArgs e)
{ {
if (SourceDatabase == null) if (SourceDatabase == null)
return; return;
string name = StringUtil.ToPascalCase(SourceDatabase.Database.Name); string name = StringUtil.ToPascalCase(SourceDatabase.Database.Name);
if (string.IsNullOrEmpty(ContextNamespace)) if (string.IsNullOrEmpty(ContextNamespace))
ContextNamespace = name + ".Data"; ContextNamespace = name + ".Data";
} }
private void OnContextNamespaceChanged(object sender, EventArgs e) private void OnContextNamespaceChanged(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(ContextNamespace)) if (string.IsNullOrEmpty(ContextNamespace))
return; return;
if (string.IsNullOrEmpty(EntityNamespace)) if (string.IsNullOrEmpty(EntityNamespace))
EntityNamespace = ContextNamespace + ".Entities"; EntityNamespace = ContextNamespace + ".Entities";
if (string.IsNullOrEmpty(MappingNamespace)) if (string.IsNullOrEmpty(MappingNamespace))
MappingNamespace = ContextNamespace + ".Mapping"; MappingNamespace = ContextNamespace + ".Mapping";
} }
</script> </script>

View File

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

View File

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

View File

@ -1,187 +1,187 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using CodeSmith.Engine; using CodeSmith.Engine;
namespace SchemaMapper namespace SchemaMapper
{ {
public enum CodeLanguage public enum CodeLanguage
{ {
CSharp, CSharp,
VisualBasic VisualBasic
} }
public static class Extensions public static class Extensions
{ {
private static readonly HashSet<string> _csharpKeywords; private static readonly HashSet<string> _csharpKeywords;
private static readonly HashSet<string> _visualBasicKeywords; private static readonly HashSet<string> _visualBasicKeywords;
private static readonly Dictionary<string, string> _csharpTypeAlias; private static readonly Dictionary<string, string> _csharpTypeAlias;
static Extensions() static Extensions()
{ {
_csharpKeywords = new HashSet<string>(StringComparer.Ordinal) _csharpKeywords = new HashSet<string>(StringComparer.Ordinal)
{ {
"as", "do", "if", "in", "is", "as", "do", "if", "in", "is",
"for", "int", "new", "out", "ref", "try", "for", "int", "new", "out", "ref", "try",
"base", "bool", "byte", "case", "char", "else", "enum", "goto", "lock", "long", "null", "this", "true", "uint", "void", "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", "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", "double", "extern", "object", "params", "public", "return", "sealed", "sizeof", "static", "string", "struct", "switch", "typeof", "unsafe", "ushort",
"checked", "decimal", "default", "finally", "foreach", "private", "virtual", "checked", "decimal", "default", "finally", "foreach", "private", "virtual",
"abstract", "continue", "delegate", "explicit", "implicit", "internal", "operator", "override", "readonly", "volatile", "abstract", "continue", "delegate", "explicit", "implicit", "internal", "operator", "override", "readonly", "volatile",
"__arglist", "__makeref", "__reftype", "interface", "namespace", "protected", "unchecked", "__arglist", "__makeref", "__reftype", "interface", "namespace", "protected", "unchecked",
"__refvalue", "stackalloc" "__refvalue", "stackalloc"
}; };
_visualBasicKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase) _visualBasicKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ {
"as", "do", "if", "in", "is", "me", "of", "on", "or", "to", "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", "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", "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", "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", "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", "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", "csbyte", "cshort", "double", "elseif", "friend", "global", "module", "mybase", "object", "option", "orelse", "public", "resume", "return", "select", "shared",
"single", "static", "string", "typeof", "ushort", "single", "static", "string", "typeof", "ushort",
"andalso", "boolean", "cushort", "decimal", "declare", "default", "finally", "gettype", "handles", "imports", "integer", "myclass", "nothing", "partial", "private", "shadows", "andalso", "boolean", "cushort", "decimal", "declare", "default", "finally", "gettype", "handles", "imports", "integer", "myclass", "nothing", "partial", "private", "shadows",
"trycast", "unicode", "variant", "trycast", "unicode", "variant",
"assembly", "continue", "delegate", "function", "inherits", "operator", "optional", "preserve", "property", "readonly", "synclock", "uinteger", "widening", "assembly", "continue", "delegate", "function", "inherits", "operator", "optional", "preserve", "property", "readonly", "synclock", "uinteger", "widening",
"addressof", "interface", "namespace", "narrowing", "overloads", "overrides", "protected", "structure", "writeonly", "addressof", "interface", "namespace", "narrowing", "overloads", "overrides", "protected", "structure", "writeonly",
"addhandler", "directcast", "implements", "paramarray", "raiseevent", "withevents", "addhandler", "directcast", "implements", "paramarray", "raiseevent", "withevents",
"mustinherit", "overridable", "mustinherit", "overridable",
"mustoverride", "mustoverride",
"removehandler", "removehandler",
"class_finalize", "notinheritable", "notoverridable", "class_finalize", "notinheritable", "notoverridable",
"class_initialize" "class_initialize"
}; };
_csharpTypeAlias = new Dictionary<string, string>(16) _csharpTypeAlias = new Dictionary<string, string>(16)
{ {
{"System.Int16", "short"}, {"System.Int16", "short"},
{"System.Int32", "int"}, {"System.Int32", "int"},
{"System.Int64", "long"}, {"System.Int64", "long"},
{"System.String", "string"}, {"System.String", "string"},
{"System.Object", "object"}, {"System.Object", "object"},
{"System.Boolean", "bool"}, {"System.Boolean", "bool"},
{"System.Void", "void"}, {"System.Void", "void"},
{"System.Char", "char"}, {"System.Char", "char"},
{"System.Byte", "byte"}, {"System.Byte", "byte"},
{"System.UInt16", "ushort"}, {"System.UInt16", "ushort"},
{"System.UInt32", "uint"}, {"System.UInt32", "uint"},
{"System.UInt64", "ulong"}, {"System.UInt64", "ulong"},
{"System.SByte", "sbyte"}, {"System.SByte", "sbyte"},
{"System.Single", "float"}, {"System.Single", "float"},
{"System.Double", "double"}, {"System.Double", "double"},
{"System.Decimal", "decimal"} {"System.Decimal", "decimal"}
}; };
} }
public static string ToCamelCase(this string name) public static string ToCamelCase(this string name)
{ {
return StringUtil.ToCamelCase(name); return StringUtil.ToCamelCase(name);
} }
public static string ToPascalCase(this string name) public static string ToPascalCase(this string name)
{ {
return StringUtil.ToPascalCase(name); return StringUtil.ToPascalCase(name);
} }
public static string ToFieldName(this string name) public static string ToFieldName(this string name)
{ {
return "_" + StringUtil.ToCamelCase(name); return "_" + StringUtil.ToCamelCase(name);
} }
public static string MakeUnique(this string name, Func<string, bool> exists) public static string MakeUnique(this string name, Func<string, bool> exists)
{ {
string uniqueName = name; string uniqueName = name;
int count = 1; int count = 1;
while (exists(uniqueName)) while (exists(uniqueName))
uniqueName = string.Concat(name, count++); uniqueName = string.Concat(name, count++);
return uniqueName; return uniqueName;
} }
public static bool IsKeyword(this string text, CodeLanguage language = CodeLanguage.CSharp) public static bool IsKeyword(this string text, CodeLanguage language = CodeLanguage.CSharp)
{ {
return language == CodeLanguage.VisualBasic return language == CodeLanguage.VisualBasic
? _visualBasicKeywords.Contains(text) ? _visualBasicKeywords.Contains(text)
: _csharpKeywords.Contains(text); : _csharpKeywords.Contains(text);
} }
public static string ToSafeName(this string name, CodeLanguage language = CodeLanguage.CSharp) public static string ToSafeName(this string name, CodeLanguage language = CodeLanguage.CSharp)
{ {
if (!name.IsKeyword(language)) if (!name.IsKeyword(language))
return name; return name;
return language == CodeLanguage.VisualBasic return language == CodeLanguage.VisualBasic
? string.Format("[{0}]", name) ? string.Format("[{0}]", name)
: "@" + name; : "@" + name;
} }
public static string ToType(this Type type, CodeLanguage language = CodeLanguage.CSharp) public static string ToType(this Type type, CodeLanguage language = CodeLanguage.CSharp)
{ {
return ToType(type.FullName, language); return ToType(type.FullName, language);
} }
public static string ToType(this string type, CodeLanguage language = CodeLanguage.CSharp) public static string ToType(this string type, CodeLanguage language = CodeLanguage.CSharp)
{ {
if (type == "System.Xml.XmlDocument") if (type == "System.Xml.XmlDocument")
type = "System.String"; type = "System.String";
string t; string t;
if (language == CodeLanguage.CSharp && _csharpTypeAlias.TryGetValue(type, out t)) if (language == CodeLanguage.CSharp && _csharpTypeAlias.TryGetValue(type, out t))
return t; return t;
return type; return type;
} }
public static string ToNullableType(this Type type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp) public static string ToNullableType(this Type type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{ {
return ToNullableType(type.FullName, isNullable, language); return ToNullableType(type.FullName, isNullable, language);
} }
public static string ToNullableType(this string type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp) public static string ToNullableType(this string type, bool isNullable = false, CodeLanguage language = CodeLanguage.CSharp)
{ {
bool isValueType = type.IsValueType(); bool isValueType = type.IsValueType();
type = type.ToType(language); type = type.ToType(language);
if (!isValueType || !isNullable) if (!isValueType || !isNullable)
return type; return type;
return language == CodeLanguage.VisualBasic return language == CodeLanguage.VisualBasic
? string.Format("Nullable(Of {0})", type) ? string.Format("Nullable(Of {0})", type)
: type + "?"; : type + "?";
} }
public static bool IsValueType(this string type) public static bool IsValueType(this string type)
{ {
if (!type.StartsWith("System.")) if (!type.StartsWith("System."))
return false; return false;
var t = Type.GetType(type, false); var t = Type.GetType(type, false);
return t != null && t.IsValueType; return t != null && t.IsValueType;
} }
public static string ToDelimitedString(this IEnumerable<string> values, string delimiter, string format = null) public static string ToDelimitedString(this IEnumerable<string> values, string delimiter, string format = null)
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
foreach (var i in values) foreach (var i in values)
{ {
if (sb.Length > 0) if (sb.Length > 0)
sb.Append(delimiter); sb.Append(delimiter);
if (string.IsNullOrEmpty(format)) if (string.IsNullOrEmpty(format))
sb.Append(i); sb.Append(i);
else else
sb.AppendFormat(format, i); sb.AppendFormat(format, i);
} }
return sb.ToString(); 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" %> <%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %> <%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %> <%@ Assembly Src="Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %> <%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %> <%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %> <%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %> <%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %> <%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity" Type="SchemaMapper.Entity" %> <%@ Property Name="Entity" Type="SchemaMapper.Entity" %>
<%@ Property Name="ContextNamespace" Type="System.String" %> <%@ Property Name="ContextNamespace" Type="System.String" %>
<%@ Property Name="EntityNamespace" Type="System.String" %> <%@ Property Name="EntityNamespace" Type="System.String" %>
<%@ Property Name="MappingNamespace" Type="System.String" %> <%@ Property Name="MappingNamespace" Type="System.String" %>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <autogenerated> // <autogenerated>
// This code was generated by a CodeSmith Template. // This code was generated by a CodeSmith Template.
// //
// DO NOT MODIFY contents of this file. Changes to this // DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated. // file will be lost if the code is regenerated.
// </autogenerated> // </autogenerated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace <%= MappingNamespace %> namespace <%= MappingNamespace %>
{ {
public partial class <%= Entity.MappingName.ToSafeName() %> public partial class <%= Entity.MappingName.ToSafeName() %>
: System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<<%= EntityNamespace %>.<%= Entity.ClassName.ToSafeName() %>> : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<<%= EntityNamespace %>.<%= Entity.ClassName.ToSafeName() %>>
{ {
public <%= Entity.MappingName.ToSafeName() %>() public <%= Entity.MappingName.ToSafeName() %>()
{ {
// table // table
<% if (string.IsNullOrEmpty(Entity.TableSchema)) { %> <% if (string.IsNullOrEmpty(Entity.TableSchema)) { %>
ToTable("<%= Entity.TableName %>"); ToTable("<%= Entity.TableName %>");
<% } else { %> <% } else { %>
ToTable("<%= Entity.TableName %>", "<%= Entity.TableSchema %>"); ToTable("<%= Entity.TableName %>", "<%= Entity.TableSchema %>");
<% } %> <% } %>
// keys // keys
<% if (Entity.Properties.PrimaryKeys.Count() > 0) { %> <% if (Entity.Properties.PrimaryKeys.Count() > 0) { %>
HasKey(t => <%= KeyExpression(Entity.Properties.PrimaryKeys, "t") %>); HasKey(t => <%= KeyExpression(Entity.Properties.PrimaryKeys, "t") %>);
<% } %> <% } %>
// Properties // Properties
<% <%
foreach(var p in Entity.Properties) foreach(var p in Entity.Properties)
{ {
Response.Write(PropertyExpression(p)); Response.Write(PropertyExpression(p));
} }
%> %>
// Relationships // Relationships
<% <%
foreach(var r in Entity.Relationships.Where(e => e.IsMapped)) foreach(var r in Entity.Relationships.Where(e => e.IsMapped))
{ {
if (r.IsManyToMany) if (r.IsManyToMany)
Response.Write(ManyToManyExpression(r)); Response.Write(ManyToManyExpression(r));
else else
Response.Write(RelationshipExpression(r)); Response.Write(RelationshipExpression(r));
} }
%> %>
} }
} }
} }
<script runat="template"> <script runat="template">
public string PropertyExpression(Property property) public string PropertyExpression(Property property)
{ {
bool isString = property.SystemType == typeof(string); bool isString = property.SystemType == typeof(string);
bool isByteArray = property.SystemType == typeof(byte[]); bool isByteArray = property.SystemType == typeof(byte[]);
bool isDecimal = property.SystemType == typeof(Decimal); bool isDecimal = property.SystemType == typeof(Decimal);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4); sb.Append(' ', 3 * 4);
sb.Append("Property(t => t."); sb.Append("Property(t => t.");
sb.Append(property.PropertyName); sb.Append(property.PropertyName);
sb.Append(")"); sb.Append(")");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasColumnName(\""); sb.Append(".HasColumnName(\"");
sb.Append(property.ColumnName); sb.Append(property.ColumnName);
sb.Append("\")"); sb.Append("\")");
if (property.IsIdentity == true) if (property.IsIdentity == true)
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)"); sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
} }
else if (property.IsAutoGenerated == true) else if (property.IsAutoGenerated == true)
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)"); sb.Append(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)");
} }
if ((isString || isByteArray) && (property.MaxLength > 0 && property.MaxLength < 8000)) if ((isString || isByteArray) && (property.MaxLength > 0 && property.MaxLength < 8000))
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasMaxLength("); sb.Append(".HasMaxLength(");
sb.Append(property.MaxLength); sb.Append(property.MaxLength);
sb.Append(")"); sb.Append(")");
} }
if (isDecimal && property.Precision.HasValue && property.Scale.HasValue) if (isDecimal && property.Precision.HasValue && property.Scale.HasValue)
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasPrecision("); sb.Append(".HasPrecision(");
sb.Append(property.Precision); sb.Append(property.Precision);
sb.Append(", "); sb.Append(", ");
sb.Append(property.Scale); sb.Append(property.Scale);
sb.Append(")"); sb.Append(")");
} }
if (property.IsRowVersion == true && isByteArray) if (property.IsRowVersion == true && isByteArray)
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".IsRowVersion()"); sb.Append(".IsRowVersion()");
} }
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
if (property.IsRequired == true) if (property.IsRequired == true)
sb.Append(".IsRequired()"); sb.Append(".IsRequired()");
else else
sb.Append(".IsOptional()"); sb.Append(".IsOptional()");
sb.AppendLine(";"); sb.AppendLine(";");
return sb.ToString(); return sb.ToString();
} }
public string ManyToManyExpression(Relationship relationship) public string ManyToManyExpression(Relationship relationship)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4); sb.Append(' ', 3 * 4);
sb.Append("HasMany(t => t."); sb.Append("HasMany(t => t.");
sb.Append(relationship.ThisPropertyName); sb.Append(relationship.ThisPropertyName);
sb.Append(")"); sb.Append(")");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t."); sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName); sb.Append(relationship.OtherPropertyName);
sb.Append(")"); sb.Append(")");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".Map(m =>"); sb.Append(".Map(m =>");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append("{"); sb.Append("{");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 5 * 4); sb.Append(' ', 5 * 4);
sb.Append("m.ToTable(\""); sb.Append("m.ToTable(\"");
sb.Append(relationship.JoinTable); sb.Append(relationship.JoinTable);
sb.Append("\", \""); sb.Append("\", \"");
sb.Append(relationship.JoinSchema); sb.Append(relationship.JoinSchema);
sb.Append("\");"); sb.Append("\");");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 5 * 4); sb.Append(' ', 5 * 4);
sb.Append("m.MapLeftKey("); sb.Append("m.MapLeftKey(");
sb.Append(relationship.JoinThisColumn.ToDelimitedString(", ", "\"{0}\"")); sb.Append(relationship.JoinThisColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");"); sb.Append(");");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 5 * 4); sb.Append(' ', 5 * 4);
sb.Append("m.MapRightKey("); sb.Append("m.MapRightKey(");
sb.Append(relationship.JoinOtherColumn.ToDelimitedString(", ", "\"{0}\"")); sb.Append(relationship.JoinOtherColumn.ToDelimitedString(", ", "\"{0}\""));
sb.Append(");"); sb.Append(");");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append("})"); sb.Append("})");
sb.Append(";"); sb.Append(";");
sb.AppendLine(); sb.AppendLine();
return sb.ToString(); return sb.ToString();
} }
public string RelationshipExpression(Relationship relationship) public string RelationshipExpression(Relationship relationship)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append(' ', 3 * 4); sb.Append(' ', 3 * 4);
if (relationship.ThisCardinality == Cardinality.One) if (relationship.ThisCardinality == Cardinality.One)
{ {
sb.Append("HasRequired(t => t."); sb.Append("HasRequired(t => t.");
sb.Append(relationship.ThisPropertyName); sb.Append(relationship.ThisPropertyName);
sb.Append(")"); sb.Append(")");
} }
else if (relationship.ThisCardinality == Cardinality.ZeroOrOne) else if (relationship.ThisCardinality == Cardinality.ZeroOrOne)
{ {
sb.Append("HasOptional(t => t."); sb.Append("HasOptional(t => t.");
sb.Append(relationship.ThisPropertyName); sb.Append(relationship.ThisPropertyName);
sb.Append(")"); sb.Append(")");
} }
if (relationship.OtherCardinality == Cardinality.Many) if (relationship.OtherCardinality == Cardinality.Many)
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".WithMany(t => t."); sb.Append(".WithMany(t => t.");
sb.Append(relationship.OtherPropertyName); sb.Append(relationship.OtherPropertyName);
sb.Append(")"); sb.Append(")");
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".HasForeignKey(d => "); sb.Append(".HasForeignKey(d => ");
sb.Append(KeyExpression(relationship.ThisProperties, "d")); sb.Append(KeyExpression(relationship.ThisProperties, "d"));
sb.Append(")"); sb.Append(")");
} }
else else
{ {
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".WithOptional(t => t."); sb.Append(".WithOptional(t => t.");
sb.Append(relationship.OtherPropertyName); sb.Append(relationship.OtherPropertyName);
sb.Append(")"); sb.Append(")");
} }
sb.AppendLine(); sb.AppendLine();
sb.Append(' ', 4 * 4); sb.Append(' ', 4 * 4);
sb.Append(".WillCascadeOnDelete("); sb.Append(".WillCascadeOnDelete(");
sb.Append(relationship.CascadeDelete == true ? "true" : "false"); sb.Append(relationship.CascadeDelete == true ? "true" : "false");
sb.Append(")"); sb.Append(")");
sb.AppendLine(";"); sb.AppendLine(";");
return sb.ToString(); return sb.ToString();
} }
public string KeyExpression(IEnumerable<Property> keys, string alias = "t") public string KeyExpression(IEnumerable<Property> keys, string alias = "t")
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (keys.Count() == 1) if (keys.Count() == 1)
{ {
sb.Append(alias); sb.Append(alias);
sb.Append("."); sb.Append(".");
sb.Append(keys.FirstOrDefault().PropertyName); sb.Append(keys.FirstOrDefault().PropertyName);
} }
else else
{ {
sb.Append("new { "); sb.Append("new { ");
foreach(var p in keys) foreach(var p in keys)
{ {
if (sb.Length > 6) if (sb.Length > 6)
sb.Append(", "); sb.Append(", ");
sb.Append(alias); sb.Append(alias);
sb.Append("."); sb.Append(".");
sb.Append(p.PropertyName); sb.Append(p.PropertyName);
} }
sb.Append(" }"); sb.Append(" }");
} }
return sb.ToString(); return sb.ToString();
} }
public string KeyExpression(IEnumerable<string> keys, string alias = "t") public string KeyExpression(IEnumerable<string> keys, string alias = "t")
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (keys.Count() == 1) if (keys.Count() == 1)
{ {
sb.Append(alias); sb.Append(alias);
sb.Append("."); sb.Append(".");
sb.Append(keys.FirstOrDefault()); sb.Append(keys.FirstOrDefault());
} }
else else
{ {
sb.Append("new { "); sb.Append("new { ");
foreach(var p in keys) foreach(var p in keys)
{ {
if (sb.Length > 6) if (sb.Length > 6)
sb.Append(", "); sb.Append(", ");
sb.Append(alias); sb.Append(alias);
sb.Append("."); sb.Append(".");
sb.Append(p); sb.Append(p);
} }
sb.Append(" }"); sb.Append(" }");
} }
return sb.ToString(); return sb.ToString();
} }
</script> </script>

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,138 +1,138 @@
<%-- <%--
Name: Database Table Properties Name: Database Table Properties
Author: yubaolee Author: yubaolee
Description: Create a list of properties from a database table Description: Create a list of properties from a database table
--%> --%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="False" Description="应用层" %> <%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="False" Description="应用层" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %> <%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Property Name="NeedViewModel" Type="Boolean" Category="Context" Default="False" Description="是否需要ViewModel" %> <%@ Property Name="NeedViewModel" Type="Boolean" Category="Context" Default="False" Description="是否需要ViewModel" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %> <%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %>
<script runat="template"> <script runat="template">
public String GetModelName() public String GetModelName()
{ {
if(NeedViewModel) if(NeedViewModel)
return ModuleName +"View"; return ModuleName +"View";
else else
return ModuleName; return ModuleName;
} }
</script> </script>
<%if(NeedViewModel){ %> <%if(NeedViewModel){ %>
using OpenAuth.App.ViewModel; using OpenAuth.App.ViewModel;
<%} %> <%} %>
using OpenAuth.Domain; using OpenAuth.Domain;
using OpenAuth.Domain.Interface; using OpenAuth.Domain.Interface;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace OpenAuth.App namespace OpenAuth.App
{ {
public class <%=ModuleName%>ManagerApp public class <%=ModuleName%>ManagerApp
{ {
private I<%=ModuleName%>Repository _repository; private I<%=ModuleName%>Repository _repository;
private IOrgRepository _orgRepository; private IOrgRepository _orgRepository;
public <%=ModuleName%>ManagerApp(I<%=ModuleName%>Repository repository, public <%=ModuleName%>ManagerApp(I<%=ModuleName%>Repository repository,
IOrgRepository orgRepository) IOrgRepository orgRepository)
{ {
_repository = repository; _repository = repository;
_orgRepository = orgRepository; _orgRepository = orgRepository;
} }
public int Get<%=GetModelName()%>CntInOrg(int orgId) public int Get<%=GetModelName()%>CntInOrg(int orgId)
{ {
if (orgId == 0) if (orgId == 0)
{ {
return _repository.Find(null).Count(); return _repository.Find(null).Count();
} }
else else
{ {
return _repository.Get<%=GetModelName()%>CntInOrgs(GetSubOrgIds(orgId)); return _repository.Get<%=GetModelName()%>CntInOrgs(GetSubOrgIds(orgId));
} }
} }
public List<<%=GetModelName()%>> LoadAll() public List<<%=GetModelName()%>> LoadAll()
{ {
return _repository.Find(null).ToList(); return _repository.Find(null).ToList();
} }
/// <summary> /// <summary>
/// 加载一个节点下面的一个或全部<%=GetModelName()%>s /// 加载一个节点下面的一个或全部<%=GetModelName()%>s
/// </summary> /// </summary>
public dynamic Load(int orgId, int pageindex, int pagesize) public dynamic Load(int orgId, int pageindex, int pagesize)
{ {
IEnumerable<<%=ModuleName%>> <%=ModuleName%>s; IEnumerable<<%=ModuleName%>> <%=ModuleName%>s;
int total = 0; int total = 0;
if (orgId == 0) if (orgId == 0)
{ {
<%=ModuleName%>s = _repository.Load<%=ModuleName%>s(pageindex, pagesize); <%=ModuleName%>s = _repository.Load<%=ModuleName%>s(pageindex, pagesize);
total = _repository.GetCount(); total = _repository.GetCount();
} }
else else
{ {
<%=ModuleName%>s = _repository.LoadInOrgs(pageindex, pagesize,GetSubOrgIds(orgId)); <%=ModuleName%>s = _repository.LoadInOrgs(pageindex, pagesize,GetSubOrgIds(orgId));
total = _repository.Get<%=ModuleName%>CntInOrgs(orgId); total = _repository.Get<%=ModuleName%>CntInOrgs(orgId);
} }
<%if(NeedViewModel){ %> <%if(NeedViewModel){ %>
var <%=ModuleName%>views = new List<<%=ModuleName%>View>(); var <%=ModuleName%>views = new List<<%=ModuleName%>View>();
foreach (var <%=ModuleName%> in <%=ModuleName%>s) foreach (var <%=ModuleName%> in <%=ModuleName%>s)
{ {
<%=ModuleName%>View uv = <%=ModuleName%>; <%=ModuleName%>View uv = <%=ModuleName%>;
uv.Organizations = string.Join(",", _orgRepository.LoadBy<%=ModuleName%>(<%=ModuleName%>.Id).Select(u => u.Name).ToList()); uv.Organizations = string.Join(",", _orgRepository.LoadBy<%=ModuleName%>(<%=ModuleName%>.Id).Select(u => u.Name).ToList());
<%=ModuleName%>views.Add(uv); <%=ModuleName%>views.Add(uv);
} }
<%} %> <%} %>
return new return new
{ {
total = total, total = total,
list = <%=GetModelName()%>s, list = <%=GetModelName()%>s,
pageCurrent = pageindex pageCurrent = pageindex
}; };
} }
/// <summary> /// <summary>
/// 获取当前节点的所有下级节点 /// 获取当前节点的所有下级节点
/// </summary> /// </summary>
private int[] GetSubOrgIds(int orgId) private int[] GetSubOrgIds(int orgId)
{ {
var org = _orgRepository.FindSingle(u => u.Id == orgId); var org = _orgRepository.FindSingle(u => u.Id == orgId);
var orgs = _orgRepository.Find(u => u.CascadeId.Contains(org.CascadeId)).Select(u => u.Id).ToArray(); var orgs = _orgRepository.Find(u => u.CascadeId.Contains(org.CascadeId)).Select(u => u.Id).ToArray();
return orgs; return orgs;
} }
public <%=GetModelName()%> Find(int id) public <%=GetModelName()%> Find(int id)
{ {
var <%=ModuleName.ToLower()%> = _repository.FindSingle(u => u.Id == id); var <%=ModuleName.ToLower()%> = _repository.FindSingle(u => u.Id == id);
if (<%=ModuleName.ToLower()%> == null) return new <%=GetModelName()%>(); if (<%=ModuleName.ToLower()%> == null) return new <%=GetModelName()%>();
return <%=ModuleName.ToLower() %>; return <%=ModuleName.ToLower() %>;
} }
public void Delete(int id) public void Delete(int id)
{ {
_repository.Delete(id); _repository.Delete(id);
} }
public void AddOrUpdate(<%=GetModelName()%> model) public void AddOrUpdate(<%=GetModelName()%> model)
{ {
<%=ModuleName%> <%=ModuleName.ToLower()%> = new <%=ModuleName%>(); <%=ModuleName%> <%=ModuleName.ToLower()%> = new <%=ModuleName%>();
model.CopyTo(<%=ModuleName.ToLower()%>); model.CopyTo(<%=ModuleName.ToLower()%>);
if (<%=ModuleName.ToLower()%>.Id == 0) if (<%=ModuleName.ToLower()%>.Id == 0)
{ {
_repository.Add(<%=ModuleName.ToLower()%>); _repository.Add(<%=ModuleName.ToLower()%>);
} }
else else
{ {
_repository.Update(<%=ModuleName.ToLower()%>); _repository.Update(<%=ModuleName.ToLower()%>);
} }
} }
} }
} }

View File

@ -1,110 +1,110 @@
<%-- <%--
Name: Database Table Properties Name: Database Table Properties
Author: yubaolee Author: yubaolee
Description: Create a list of properties from a database table Description: Create a list of properties from a database table
--%> --%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="False" Description="控制器" %> <%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="False" Description="控制器" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %> <%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Property Name="NeedViewModel" Type="Boolean" Category="Context" Default="False" Description="是否需要ViewModel" %> <%@ Property Name="NeedViewModel" Type="Boolean" Category="Context" Default="False" Description="是否需要ViewModel" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %> <%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %>
<script runat="template"> <script runat="template">
public String GetModelName() public String GetModelName()
{ {
if(NeedViewModel) if(NeedViewModel)
return ModuleName +"View"; return ModuleName +"View";
else else
return ModuleName; return ModuleName;
} }
</script> </script>
using System; using System;
using System.Web.Mvc; using System.Web.Mvc;
using Infrastructure; using Infrastructure;
using OpenAuth.App; using OpenAuth.App;
<%if(NeedViewModel){ %> <%if(NeedViewModel){ %>
using OpenAuth.App.ViewModel; using OpenAuth.App.ViewModel;
<%} %> <%} %>
using OpenAuth.Domain; using OpenAuth.Domain;
namespace OpenAuth.Mvc.Controllers namespace OpenAuth.Mvc.Controllers
{ {
public class <%=ModuleName%>ManagerController : BaseController public class <%=ModuleName%>ManagerController : BaseController
{ {
private <%=ModuleName%>ManagerApp _app; private <%=ModuleName%>ManagerApp _app;
public <%=ModuleName%>ManagerController() public <%=ModuleName%>ManagerController()
{ {
_app = AutofacExt.GetFromFac<<%=ModuleName%>ManagerApp>(); _app = AutofacExt.GetFromFac<<%=ModuleName%>ManagerApp>();
} }
// //
// GET: /UserManager/ // GET: /UserManager/
public ActionResult Index() public ActionResult Index()
{ {
return View(); return View();
} }
public ActionResult Add(int id = 0) public ActionResult Add(int id = 0)
{ {
return View(_app.Find(id)); return View(_app.Find(id));
} }
//添加或修改<%=ModuleName %> //添加或修改<%=ModuleName %>
[HttpPost] [HttpPost]
public string Add(<%=GetModelName()%> model) public string Add(<%=GetModelName()%> model)
{ {
try try
{ {
_app.AddOrUpdate(model); _app.AddOrUpdate(model);
} }
catch (Exception ex) catch (Exception ex)
{ {
BjuiResponse.statusCode = "300"; BjuiResponse.statusCode = "300";
BjuiResponse.message = ex.Message; BjuiResponse.message = ex.Message;
} }
return JsonHelper.Instance.Serialize(BjuiResponse); return JsonHelper.Instance.Serialize(BjuiResponse);
} }
/// <summary> /// <summary>
/// 加载节点下面的所有<%=ModuleName %>s /// 加载节点下面的所有<%=ModuleName %>s
/// </summary> /// </summary>
public string Load(int parentId, int pageCurrent = 1, int pageSize = 30) public string Load(int parentId, int pageCurrent = 1, int pageSize = 30)
{ {
return JsonHelper.Instance.Serialize(_app.Load(parentId, pageCurrent, pageSize)); return JsonHelper.Instance.Serialize(_app.Load(parentId, pageCurrent, pageSize));
} }
public string LoadForTree() public string LoadForTree()
{ {
var models = _app.LoadAll(); var models = _app.LoadAll();
//添加根节点 //添加根节点
models.Add(new <%=ModuleName %> models.Add(new <%=ModuleName %>
{ {
Id = 0, Id = 0,
ParentId = -1, ParentId = -1,
Name = "根结点", Name = "根结点",
CascadeId = "0" CascadeId = "0"
}); });
return JsonHelper.Instance.Serialize(models); return JsonHelper.Instance.Serialize(models);
} }
public string Delete(int Id) public string Delete(int Id)
{ {
try try
{ {
_app.Delete(Id); _app.Delete(Id);
} }
catch (Exception e) catch (Exception e)
{ {
BjuiResponse.statusCode = "300"; BjuiResponse.statusCode = "300";
BjuiResponse.message = e.Message; BjuiResponse.message = e.Message;
} }
return JsonHelper.Instance.Serialize(BjuiResponse); return JsonHelper.Instance.Serialize(BjuiResponse);
} }
} }
} }

View File

@ -1,105 +1,105 @@
<%-- <%--
Name: 列表页面 Name: 列表页面
Author: yubaolee Author: yubaolee
Description: 列表页面 Description: 列表页面
--%> --%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Encoding="utf-8" Description="添加模块" %> <%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Encoding="utf-8" Description="添加模块" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context"
Description="连接的数据库" %> Description="连接的数据库" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %> <%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %> <%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %>
<%@ Assembly Src="Util.cs" %> <%@ Assembly Src="Util.cs" %>
<%@ Import Namespace="Util" %> <%@ Import Namespace="Util" %>
@section header @section header
{ {
<link rel="stylesheet" href="/css/treetable.css" /> <link rel="stylesheet" href="/css/treetable.css" />
} }
<blockquote class="layui-elem-quote news_search toolList"> <blockquote class="layui-elem-quote news_search toolList">
<div class="layui-inline"> <div class="layui-inline">
<div class="layui-input-inline"> <div class="layui-input-inline">
<input class="layui-input" placeholder="请输入关键字" <input class="layui-input" placeholder="请输入关键字"
name="key" id="key" autocomplete="off"> name="key" id="key" autocomplete="off">
</div> </div>
<button class="layui-btn" data-type="search">搜索</button> <button class="layui-btn" data-type="search">搜索</button>
</div> </div>
@Html.Action("MenuHeader", "Home") @Html.Action("MenuHeader", "Home")
@*<button class="layui-btn " data-type="refresh">刷新</button> @*<button class="layui-btn " data-type="refresh">刷新</button>
<button class="layui-btn " data-type="addData">添加</button> <button class="layui-btn " data-type="addData">添加</button>
<button class="layui-btn layui-btn-danger" data-type="del">批量删除</button>*@ <button class="layui-btn layui-btn-danger" data-type="del">批量删除</button>*@
</blockquote> </blockquote>
<div style="display: flex;"> <div style="display: flex;">
<ul id="tree" class="ztree" style="display: inline-block; width: 180px; padding: 10px; border: 1px solid #ddd; overflow: auto;"></ul> <ul id="tree" class="ztree" style="display: inline-block; width: 180px; padding: 10px; border: 1px solid #ddd; overflow: auto;"></ul>
<table class="layui-table" <table class="layui-table"
lay-data="{height: 'full-80', page:true, id:'mainList'}" lay-data="{height: 'full-80', page:true, id:'mainList'}"
lay-filter="list"> lay-filter="list">
<thead> <thead>
<tr> <tr>
<th lay-data="{checkbox:true, fixed: true}"></th> <th lay-data="{checkbox:true, fixed: true}"></th>
<% foreach (ColumnSchema column in this.SourceTable.Columns) {%> <% foreach (ColumnSchema column in this.SourceTable.Columns) {%>
<th lay-data="{field:'<%=column.Name%>', width:150}"><%=Tools.GetDescription(column)%></th> <th lay-data="{field:'<%=column.Name%>', width:150}"><%=Tools.GetDescription(column)%></th>
<% }%> <% }%>
<th lay-data="{fixed: 'right', width:160, align:'center', toolbar: '#barList'}"></th> <th lay-data="{fixed: 'right', width:160, align:'center', toolbar: '#barList'}"></th>
</tr> </tr>
</thead> </thead>
</table> </table>
</div> </div>
<script type="text/html" id="barList"> <script type="text/html" id="barList">
<a class="layui-btn layui-btn-primary layui-btn-mini" lay-event="detail">查看</a> <a class="layui-btn layui-btn-primary layui-btn-mini" lay-event="detail">查看</a>
</script> </script>
<!--用户添加/编辑窗口--> <!--用户添加/编辑窗口-->
<div id="divEdit" style="display: none"> <div id="divEdit" style="display: none">
<form class="layui-form" action="" id="formEdit"> <form class="layui-form" action="" id="formEdit">
<% foreach (ColumnSchema column in this.SourceTable.Columns) { <% foreach (ColumnSchema column in this.SourceTable.Columns) {
if(column.IsPrimaryKeyMember){%> if(column.IsPrimaryKeyMember){%>
<input type="hidden" name="<%=column.Name%>" v-model="<%=column.Name%>" /> <input type="hidden" name="<%=column.Name%>" v-model="<%=column.Name%>" />
<%}else if(CSharpAlias[column.SystemType.FullName] == "bool") {%> <%}else if(CSharpAlias[column.SystemType.FullName] == "bool") {%>
<div class="layui-form-item"> <div class="layui-form-item">
<label class="layui-form-label"><%=Tools.GetDescription(column)%></label> <label class="layui-form-label"><%=Tools.GetDescription(column)%></label>
<div class="layui-input-block"> <div class="layui-input-block">
<input type="checkbox" name="<%=column.Name%>" v-model="<%=column.Name%>" lay-skin="switch" value="1"> <input type="checkbox" name="<%=column.Name%>" v-model="<%=column.Name%>" lay-skin="switch" value="1">
</div> </div>
</div> </div>
<%}else if(CSharpAlias[column.SystemType.FullName] == "int" ) {%> <%}else if(CSharpAlias[column.SystemType.FullName] == "int" ) {%>
<div class="layui-form-item"> <div class="layui-form-item">
<label class="layui-form-label"><%=Tools.GetDescription(column)%></label> <label class="layui-form-label"><%=Tools.GetDescription(column)%></label>
<div class="layui-input-block"> <div class="layui-input-block">
<input type="radio" name="<%=column.Name%>" value="1" title="value1" checked> <input type="radio" name="<%=column.Name%>" value="1" title="value1" checked>
<input type="radio" name="<%=column.Name%>" value="0" title="value2"> <input type="radio" name="<%=column.Name%>" value="0" title="value2">
</div> </div>
</div> </div>
<%} else {%> <%} else {%>
<div class="layui-form-item"> <div class="layui-form-item">
<label class="layui-form-label"><%=Tools.GetDescription(column)%></label> <label class="layui-form-label"><%=Tools.GetDescription(column)%></label>
<div class="layui-input-block"> <div class="layui-input-block">
<input type="text" name="<%=column.Name%>" v-model="<%=column.Name%>" required lay-verify="required" <input type="text" name="<%=column.Name%>" v-model="<%=column.Name%>" required lay-verify="required"
placeholder="<%=Tools.GetDescription(column)%>" autocomplete="off" class="layui-input"> placeholder="<%=Tools.GetDescription(column)%>" autocomplete="off" class="layui-input">
</div> </div>
</div> </div>
<%} %> <%} %>
<%} %> <%} %>
<%if(Tools.NeedCascade(SourceTable)){ %> <%if(Tools.NeedCascade(SourceTable)){ %>
<div class="layui-form-item"> <div class="layui-form-item">
<label class="layui-form-label">所属部门</label> <label class="layui-form-label">所属部门</label>
<div class="layui-input-block"> <div class="layui-input-block">
<input id="Organizations" name="Organizations" v-model="Organizations" required lay-verify="required" class="layui-input" /> <input id="Organizations" name="Organizations" v-model="Organizations" required lay-verify="required" class="layui-input" />
<input id="OrganizationIds" name="OrganizationIds" v-model="OrganizationIds" required lay-verify="required" type="hidden" /> <input id="OrganizationIds" name="OrganizationIds" v-model="OrganizationIds" required lay-verify="required" type="hidden" />
<div id="menuContent" class="menuContent" style="display: none;"> <div id="menuContent" class="menuContent" style="display: none;">
<ul id="org" class="ztree"></ul> <ul id="org" class="ztree"></ul>
</div> </div>
</div> </div>
</div> </div>
<%} %> <%} %>
</form> </form>
</div> </div>
<script type="text/javascript" src="/layui/layui.js"></script> <script type="text/javascript" src="/layui/layui.js"></script>
<script type="text/javascript" src="/js/<%=ModuleName%>Manager.js"></script> <script type="text/javascript" src="/js/<%=ModuleName%>Manager.js"></script>

View File

@ -1,24 +1,24 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using CodeSmith.Engine; using CodeSmith.Engine;
using SchemaExplorer; using SchemaExplorer;
namespace Util{ namespace Util{
public class Tools{ public class Tools{
public static String GetDescription(ColumnSchema column) { //得到字段的描述 public static String GetDescription(ColumnSchema column) { //得到字段的描述
if(string.IsNullOrEmpty(column.Description)) if(string.IsNullOrEmpty(column.Description))
return column.Name; return column.Name;
else else
return column.Description; return column.Description;
} }
public static bool NeedCascade(TableSchema SourceTable){ //判断表中是否需要下拉选择树 public static bool NeedCascade(TableSchema SourceTable){ //判断表中是否需要下拉选择树
return SourceTable.Columns.Contains("ParentId") return SourceTable.Columns.Contains("ParentId")
|| SourceTable.Columns.Contains("CascadeId") ; || SourceTable.Columns.Contains("CascadeId") ;
} }
} }
} }

View File

@ -1,166 +1,166 @@
<%-- <%--
Name: 主JS界面 Name: 主JS界面
Author: yubaolee Author: yubaolee
--%> --%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Encoding="utf-8" Description="添加模块" %> <%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Encoding="utf-8" Description="添加模块" %>
<%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %> <%@ Property Name="ModuleName" Type="String" Category="Context" Description="模块名称" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %> <%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %>
<%@ Assembly Src="Util.cs" %> <%@ Assembly Src="Util.cs" %>
<%@ Import Namespace="Util" %> <%@ Import Namespace="Util" %>
layui.config({ layui.config({
base: "/js/" base: "/js/"
}).use(['form','vue', 'ztree', 'layer', 'jquery', 'table','droptree','openauth'], function () { }).use(['form','vue', 'ztree', 'layer', 'jquery', 'table','droptree','openauth'], function () {
var form = layui.form, var form = layui.form,
//layer = (parent == undefined || parent.layer === undefined )? layui.layer : parent.layer, //layer = (parent == undefined || parent.layer === undefined )? layui.layer : parent.layer,
layer = layui.layer, layer = layui.layer,
$ = layui.jquery; $ = layui.jquery;
var table = layui.table; var table = layui.table;
var openauth = layui.openauth; var openauth = layui.openauth;
layui.droptree("/UserSession/GetOrgs", "#Organizations", "#OrganizationIds"); layui.droptree("/UserSession/GetOrgs", "#Organizations", "#OrganizationIds");
//主列表加载,可反复调用进行刷新 //主列表加载,可反复调用进行刷新
var config= {}; //table的参数如搜索key点击tree的id var config= {}; //table的参数如搜索key点击tree的id
var mainList = function (options) { var mainList = function (options) {
if (options != undefined) { if (options != undefined) {
$.extend(config, options); $.extend(config, options);
} }
table.reload('mainList', { table.reload('mainList', {
url: '/<%=ModuleName%>Manager/Load', url: '/<%=ModuleName%>Manager/Load',
where: config where: config
}); });
} }
//左边树状机构列表 //左边树状机构列表
var ztree = function () { var ztree = function () {
var url = '/UserSession/GetOrgs'; var url = '/UserSession/GetOrgs';
var zTreeObj; var zTreeObj;
var setting = { var setting = {
view: { selectedMulti: false }, view: { selectedMulti: false },
data: { data: {
key: { key: {
name: 'Name', name: 'Name',
title: 'Name' title: 'Name'
}, },
simpleData: { simpleData: {
enable: true, enable: true,
idKey: 'Id', idKey: 'Id',
pIdKey: 'ParentId', pIdKey: 'ParentId',
rootPId: 'null' rootPId: 'null'
} }
}, },
callback: { callback: {
onClick: function (event, treeId, treeNode) { onClick: function (event, treeId, treeNode) {
mainList({ orgId: treeNode.Id }); mainList({ orgId: treeNode.Id });
} }
} }
}; };
var load = function () { var load = function () {
$.getJSON(url, function (json) { $.getJSON(url, function (json) {
zTreeObj = $.fn.zTree.init($("#tree"), setting, json); zTreeObj = $.fn.zTree.init($("#tree"), setting, json);
mainList({ orgId: json[0].Id }); mainList({ orgId: json[0].Id });
zTreeObj.expandAll(true); zTreeObj.expandAll(true);
}); });
}; };
load(); load();
return { return {
reload: load reload: load
} }
}(); }();
//添加(编辑)对话框 //添加(编辑)对话框
var editDlg = function() { var editDlg = function() {
var vm = new Vue({ var vm = new Vue({
el: "#formEdit" el: "#formEdit"
}); });
var update = false; //是否为更新 var update = false; //是否为更新
var show = function (data) { var show = function (data) {
var title = update ? "编辑信息" : "添加"; var title = update ? "编辑信息" : "添加";
layer.open({ layer.open({
title: title, title: title,
area: ["500px", "400px"], area: ["500px", "400px"],
type: 1, type: 1,
content: $('#divEdit'), content: $('#divEdit'),
success: function() { success: function() {
vm.$set('$data', data); vm.$set('$data', data);
}, },
end: mainList end: mainList
}); });
var url = "/<%=ModuleName%>Manager/Add"; var url = "/<%=ModuleName%>Manager/Add";
if (update) { if (update) {
url = "/<%=ModuleName%>Manager/Update"; //暂时和添加一个地址 url = "/<%=ModuleName%>Manager/Update"; //暂时和添加一个地址
} }
//提交数据 //提交数据
form.on('submit(formSubmit)', form.on('submit(formSubmit)',
function(data) { function(data) {
$.post(url, $.post(url,
data.field, data.field,
function(data) { function(data) {
layer.msg(data.Message); layer.msg(data.Message);
}, },
"json"); "json");
return false; return false;
}); });
} }
return { return {
add: function() { //弹出添加 add: function() { //弹出添加
update = false; update = false;
show({ show({
Id: '' Id: ''
}); });
}, },
update: function(data) { //弹出编辑框 update: function(data) { //弹出编辑框
update = true; update = true;
show(data); show(data);
} }
}; };
}(); }();
//监听表格内部按钮 //监听表格内部按钮
table.on('tool(list)', function (obj) { table.on('tool(list)', function (obj) {
var data = obj.data; var data = obj.data;
if (obj.event === 'detail') { //查看 if (obj.event === 'detail') { //查看
layer.msg('ID' + data.Id + ' 的查看操作'); layer.msg('ID' + data.Id + ' 的查看操作');
} }
}); });
//监听页面主按钮操作 //监听页面主按钮操作
var active = { var active = {
btnDel: function () { //批量删除 btnDel: function () { //批量删除
var checkStatus = table.checkStatus('mainList') var checkStatus = table.checkStatus('mainList')
, data = checkStatus.data; , data = checkStatus.data;
openauth.del("/<%=ModuleName%>Manager/Delete", openauth.del("/<%=ModuleName%>Manager/Delete",
data.map(function (e) { return e.Id; }), data.map(function (e) { return e.Id; }),
mainList); mainList);
} }
, btnAdd: function () { //添加 , btnAdd: function () { //添加
editDlg.add(); editDlg.add();
} }
, btnEdit: function () { //编辑 , btnEdit: function () { //编辑
var checkStatus = table.checkStatus('mainList') var checkStatus = table.checkStatus('mainList')
, data = checkStatus.data; , data = checkStatus.data;
if (data.length != 1) { if (data.length != 1) {
layer.msg("请选择编辑的行,且同时只能编辑一行"); layer.msg("请选择编辑的行,且同时只能编辑一行");
return; return;
} }
editDlg.update(data[0]); editDlg.update(data[0]);
} }
, search: function () { //搜索 , search: function () { //搜索
mainList({ key: $('#key').val() }); mainList({ key: $('#key').val() });
} }
, btnRefresh: function() { , btnRefresh: function() {
mainList(); mainList();
} }
}; };
$('.toolList .layui-btn').on('click', function () { $('.toolList .layui-btn').on('click', function () {
var type = $(this).data('type'); var type = $(this).data('type');
active[type] ? active[type].call(this) : ''; active[type] ? active[type].call(this) : '';
}); });
//监听页面主按钮操作 end //监听页面主按钮操作 end
}) })

View File

@ -1,146 +1,146 @@
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %> <%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="None" %>
<%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %> <%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Assembly Name="Mono.Cecil" Path="..\Common" %> <%@ Assembly Name="Mono.Cecil" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %> <%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %> <%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %>
<%@ Assembly Src="Internal\Model.cs" %> <%@ Assembly Src="Internal\Model.cs" %>
<%@ Assembly Src="Internal\Extensions.cs" %> <%@ Assembly Src="Internal\Extensions.cs" %>
<%@ Assembly Src="Internal\Generator.cs" %> <%@ Assembly Src="Internal\Generator.cs" %>
<%@ Assembly Src="Internal\Parser.cs" %> <%@ Assembly Src="Internal\Parser.cs" %>
<%@ Import Namespace="System.Collections.Generic" %> <%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Linq" %> <%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %> <%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %> <%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="SchemaMapper" %> <%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="SourceTable" <%@ Property Name="SourceTable"
Type="SchemaExplorer.TableSchema" Type="SchemaExplorer.TableSchema"
Category="Context" Category="Context"
Description="连接的数据库" Description="连接的数据库"
OnChanged="OnSourceDatabaseChanged"%> OnChanged="OnSourceDatabaseChanged"%>
<%@ Property Name="ModuleName" <%@ Property Name="ModuleName"
Type="System.String" Type="System.String"
Description="模块名称User"%> Description="模块名称User"%>
<%@ Property Name="directory" <%@ Property Name="directory"
Type="System.String" Type="System.String"
Default=".\" Default=".\"
Optional="True" Optional="True"
Description="代码生成路径" Description="代码生成路径"
Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %> Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
<%@ Property Name="NeedViewModel" <%@ Property Name="NeedViewModel"
Type="Boolean" Type="Boolean"
Default="False" Default="False"
Optional="True" Optional="True"
Description="是否需要ViewModel" %> Description="是否需要ViewModel" %>
<%@ Register Name="ApplicationGenerateClass" <%@ Register Name="ApplicationGenerateClass"
Template="Web\Application.cst" Template="Web\Application.cst"
MergeProperties="False" %> MergeProperties="False" %>
<%@ Register Name="HtmlGenerateClass" <%@ Register Name="HtmlGenerateClass"
Template="Web\Index.cshtml.cst" Template="Web\Index.cshtml.cst"
MergeProperties="False" %> MergeProperties="False" %>
<%@ Register Name="JSGenerateClass" <%@ Register Name="JSGenerateClass"
Template="Web\index.js.cst" Template="Web\index.js.cst"
MergeProperties="False" %> MergeProperties="False" %>
Generating Entities ... Generating Entities ...
<% Generate(); %> <% Generate(); %>
<script runat="template"> <script runat="template">
public void Generate() public void Generate()
{ {
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
string outputDirectory = Path.GetFullPath(directory); string outputDirectory = Path.GetFullPath(directory);
if (!Directory.Exists(directory)) //根目录 if (!Directory.Exists(directory)) //根目录
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
if (!Directory.Exists(directory +"/views")) //视图根文件夹 if (!Directory.Exists(directory +"/views")) //视图根文件夹
Directory.CreateDirectory(directory +"/views"); Directory.CreateDirectory(directory +"/views");
if (!Directory.Exists(directory +"/js")) //js根目录 if (!Directory.Exists(directory +"/js")) //js根目录
Directory.CreateDirectory(directory +"/js"); Directory.CreateDirectory(directory +"/js");
if (!Directory.Exists(directory +"/views/"+ModuleName +"Manager")) //视图文件夹 if (!Directory.Exists(directory +"/views/"+ModuleName +"Manager")) //视图文件夹
Directory.CreateDirectory(directory +"/views/"+ModuleName +"Manager"); Directory.CreateDirectory(directory +"/views/"+ModuleName +"Manager");
CreateApplicationClass(); CreateApplicationClass();
CreateHtmlClass(); CreateHtmlClass();
CreateJSClass(); CreateJSClass();
this.RegisterReference("System.Configuration"); this.RegisterReference("System.Configuration");
this.RegisterReference("System.Data"); this.RegisterReference("System.Data");
this.RegisterReference("System.Data.Entity"); this.RegisterReference("System.Data.Entity");
this.RegisterReference("System.Runtime.Serialization"); this.RegisterReference("System.Runtime.Serialization");
this.RegisterReference("EntityFramework"); this.RegisterReference("EntityFramework");
watch.Stop(); watch.Stop();
Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms"); Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms");
} }
//创建APP层,如UserManagerApp.cs //创建APP层,如UserManagerApp.cs
public void CreateApplicationClass() public void CreateApplicationClass()
{ {
ApplicationGenerateClass generatedClass = this.Create<ApplicationGenerateClass>(); ApplicationGenerateClass generatedClass = this.Create<ApplicationGenerateClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
string rootDirectory = Path.GetFullPath(directory); string rootDirectory = Path.GetFullPath(directory);
string generatedFile = ModuleName + "ManagerApp.cs"; string generatedFile = ModuleName + "ManagerApp.cs";
generatedFile = Path.Combine(rootDirectory, generatedFile); generatedFile = Path.Combine(rootDirectory, generatedFile);
generatedClass.ModuleName = ModuleName; generatedClass.ModuleName = ModuleName;
generatedClass.NeedViewModel = NeedViewModel; generatedClass.NeedViewModel = NeedViewModel;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
//创建视图,如views/Users/index.html //创建视图,如views/Users/index.html
public void CreateHtmlClass() public void CreateHtmlClass()
{ {
HtmlGenerateClass generatedClass = this.Create<HtmlGenerateClass>(); HtmlGenerateClass generatedClass = this.Create<HtmlGenerateClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
string generatedFile = Path.GetFullPath(directory) + "/views/"+ModuleName+"Manager/" + "index.cshtml"; string generatedFile = Path.GetFullPath(directory) + "/views/"+ModuleName+"Manager/" + "index.cshtml";
generatedClass.ModuleName = ModuleName; generatedClass.ModuleName = ModuleName;
generatedClass.SourceTable = SourceTable; generatedClass.SourceTable = SourceTable;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
//创建视图,如js/userManager.js //创建视图,如js/userManager.js
public void CreateJSClass() public void CreateJSClass()
{ {
JSGenerateClass generatedClass = this.Create<JSGenerateClass>(); JSGenerateClass generatedClass = this.Create<JSGenerateClass>();
this.CopyPropertiesTo(generatedClass); this.CopyPropertiesTo(generatedClass);
string generatedFile = Path.GetFullPath(directory) + "/js/"+ModuleName+"Manager.js"; string generatedFile = Path.GetFullPath(directory) + "/js/"+ModuleName+"Manager.js";
generatedClass.ModuleName = ModuleName; generatedClass.ModuleName = ModuleName;
Response.WriteLine(generatedFile); Response.WriteLine(generatedFile);
generatedClass.RenderToFile(generatedFile, generatedFile, true); generatedClass.RenderToFile(generatedFile, generatedFile, true);
} }
//更换数据源时改变ModuleName //更换数据源时改变ModuleName
private void OnSourceDatabaseChanged(object sender, EventArgs e) private void OnSourceDatabaseChanged(object sender, EventArgs e)
{ {
if (SourceTable == null) if (SourceTable == null)
return; return;
ModuleName = SourceTable.Name; ModuleName = SourceTable.Name;
} }
</script> </script>

View File

@ -13,7 +13,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenAuth.Domain; using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
namespace OpenAuth.App namespace OpenAuth.App
{ {
@ -21,9 +20,9 @@ namespace OpenAuth.App
/// 领域服务 /// 领域服务
/// <para>用户授权服务</para> /// <para>用户授权服务</para>
/// </summary> /// </summary>
public class AuthoriseService public class AuthoriseService :BaseApp<User>
{ {
public IUnitWork _unitWork { get; set; }
protected User _user; protected User _user;
private List<string> _userRoleIds; //用户角色GUID private List<string> _userRoleIds; //用户角色GUID
@ -59,13 +58,13 @@ namespace OpenAuth.App
set set
{ {
_user = value; _user = value;
_userRoleIds = _unitWork.Find<Relevance>(u => u.FirstId == _user.Id && u.Key == "UserRole").Select(u => u.SecondId).ToList(); _userRoleIds = UnitWork.Find<Relevance>(u => u.FirstId == _user.Id && u.Key == "UserRole").Select(u => u.SecondId).ToList();
} }
} }
public void Check(string userName, string password) public void Check(string userName, string password)
{ {
var _user = _unitWork.FindSingle<User>(u => u.Account == userName); var _user = Repository.FindSingle(u => u.Account == userName);
if (_user == null) if (_user == null)
{ {
throw new Exception("用户帐号不存在"); throw new Exception("用户帐号不存在");
@ -79,11 +78,11 @@ namespace OpenAuth.App
/// <returns>IQueryable&lt;Org&gt;.</returns> /// <returns>IQueryable&lt;Org&gt;.</returns>
public virtual IQueryable<Org> GetOrgsQuery() public virtual IQueryable<Org> GetOrgsQuery()
{ {
var orgids = _unitWork.Find<Relevance>( var orgids = UnitWork.Find<Relevance>(
u => u =>
(u.FirstId == _user.Id && u.Key == "UserOrg") || (u.FirstId == _user.Id && u.Key == "UserOrg") ||
(u.Key == "RoleOrg" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId); (u.Key == "RoleOrg" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId);
return _unitWork.Find<Org>(u => orgids.Contains(u.Id)); return UnitWork.Find<Org>(u => orgids.Contains(u.Id));
} }
/// <summary> /// <summary>
@ -92,11 +91,11 @@ namespace OpenAuth.App
/// <returns>IQueryable&lt;Resource&gt;.</returns> /// <returns>IQueryable&lt;Resource&gt;.</returns>
public virtual IQueryable<Resource> GetResourcesQuery() public virtual IQueryable<Resource> GetResourcesQuery()
{ {
var resourceIds = _unitWork.Find<Relevance>( var resourceIds = UnitWork.Find<Relevance>(
u => u =>
(u.FirstId == _user.Id && u.Key == "UserResource") || (u.FirstId == _user.Id && u.Key == "UserResource") ||
(u.Key == "RoleResource" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId); (u.Key == "RoleResource" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId);
return _unitWork.Find<Resource>(u => resourceIds.Contains(u.Id)); return UnitWork.Find<Resource>(u => resourceIds.Contains(u.Id));
} }
/// <summary> /// <summary>
@ -104,11 +103,11 @@ namespace OpenAuth.App
/// </summary> /// </summary>
public virtual IQueryable<ModuleElement> GetModuleElementsQuery() public virtual IQueryable<ModuleElement> GetModuleElementsQuery()
{ {
var elementIds = _unitWork.Find<Relevance>( var elementIds = UnitWork.Find<Relevance>(
u => u =>
(u.FirstId == _user.Id && u.Key == "UserElement") || (u.FirstId == _user.Id && u.Key == "UserElement") ||
(u.Key == "RoleElement" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId); (u.Key == "RoleElement" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId);
return _unitWork.Find<ModuleElement>(u => elementIds.Contains(u.Id)); return UnitWork.Find<ModuleElement>(u => elementIds.Contains(u.Id));
} }
/// <summary> /// <summary>
@ -116,17 +115,17 @@ namespace OpenAuth.App
/// </summary> /// </summary>
public virtual IQueryable<Module> GetModulesQuery() public virtual IQueryable<Module> GetModulesQuery()
{ {
var moduleIds = _unitWork.Find<Relevance>( var moduleIds = UnitWork.Find<Relevance>(
u => u =>
(u.FirstId == _user.Id && u.Key == "UserModule") || (u.FirstId == _user.Id && u.Key == "UserModule") ||
(u.Key == "RoleModule" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId); (u.Key == "RoleModule" && _userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId);
return _unitWork.Find<Module>(u => moduleIds.Contains(u.Id)).OrderBy(u => u.SortNo); return UnitWork.Find<Module>(u => moduleIds.Contains(u.Id)).OrderBy(u => u.SortNo);
} }
//用户角色 //用户角色
public virtual IQueryable<Role> GetRolesQuery() public virtual IQueryable<Role> GetRolesQuery()
{ {
return _unitWork.Find<Role>(u => _userRoleIds.Contains(u.Id)); return UnitWork.Find<Role>(u => _userRoleIds.Contains(u.Id));
} }
} }
} }

24
OpenAuth.App/BaseApp.cs Normal file
View File

@ -0,0 +1,24 @@
using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
namespace OpenAuth.App
{
/// <summary>
/// 业务层基类UnitWork用于事务操作Repository用于普通的数据库操作
/// <para>如用户管理Class UserManagerApp:BaseApp<User></para>
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseApp<T> where T:Entity
{
/// <summary>
/// 用于事务操作
/// </summary>
/// <value>The unit work.</value>
public IUnitWork UnitWork { get; set; }
/// <summary>
/// 用于普通的数据库操作
/// </summary>
/// <value>The repository.</value>
public IRepository<T> Repository { get; set; }
}
}

View File

@ -81,6 +81,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="AuthoriseService.cs" /> <Compile Include="AuthoriseService.cs" />
<Compile Include="BaseApp.cs" />
<Compile Include="CategoryManagerApp.cs" /> <Compile Include="CategoryManagerApp.cs" />
<Compile Include="AuthorizeApp.cs" /> <Compile Include="AuthorizeApp.cs" />
<Compile Include="Extention\IWF_Runtime.cs" /> <Compile Include="Extention\IWF_Runtime.cs" />

View File

@ -2,6 +2,7 @@
using OpenAuth.Domain; using OpenAuth.Domain;
using OpenAuth.Domain.Interface; using OpenAuth.Domain.Interface;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace OpenAuth.App namespace OpenAuth.App
@ -89,5 +90,26 @@ namespace OpenAuth.App
}).ToArray()); }).ToArray());
_unitWork.Save(); _unitWork.Save();
} }
/// <summary>
/// 根据关联表的一个键获取另外键的值
/// </summary>
/// <param name="key">映射标识</param>
/// <param name="returnSecondIds">返回的是否为映射表的第二列,如果不是则返回第一列</param>
/// <param name="ids">已知的ID列表</param>
/// <returns>List&lt;System.String&gt;.</returns>
public List<string> Get(string key, bool returnSecondIds, params string[] ids)
{
if (returnSecondIds)
{
return _unitWork.Find<Relevance>(u => u.Key == key
&& ids.Contains(u.FirstId)).Select(u => u.SecondId).ToList();
}
else
{
return _unitWork.Find<Relevance>(u => u.Key == key
&& ids.Contains(u.SecondId)).Select(u => u.FirstId).ToList();
}
}
} }
} }

View File

@ -29,28 +29,28 @@ namespace OpenAuth.App
public override IQueryable<Org> GetOrgsQuery() public override IQueryable<Org> GetOrgsQuery()
{ {
return _unitWork.Find<Org>(null); return UnitWork.Find<Org>(null);
} }
public override IQueryable<Resource> GetResourcesQuery() public override IQueryable<Resource> GetResourcesQuery()
{ {
return _unitWork.Find<Resource>(null); return UnitWork.Find<Resource>(null);
} }
public override IQueryable<ModuleElement> GetModuleElementsQuery() public override IQueryable<ModuleElement> GetModuleElementsQuery()
{ {
return _unitWork.Find<ModuleElement>(null); return UnitWork.Find<ModuleElement>(null);
} }
public override IQueryable<Module> GetModulesQuery() public override IQueryable<Module> GetModulesQuery()
{ {
return _unitWork.Find<Module>(null); return UnitWork.Find<Module>(null);
} }
public override IQueryable<Role> GetRolesQuery() public override IQueryable<Role> GetRolesQuery()
{ {
//用户角色 //用户角色
return _unitWork.Find<Role>(null); return UnitWork.Find<Role>(null);
} }
} }
} }

View File

@ -1,6 +1,5 @@
using OpenAuth.App.ViewModel; using OpenAuth.App.ViewModel;
using OpenAuth.Domain; using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -9,15 +8,14 @@ using OpenAuth.App.Request;
namespace OpenAuth.App namespace OpenAuth.App
{ {
public class UserManagerApp public class UserManagerApp :BaseApp<User>
{ {
public IUnitWork _unitWork { get; set; }
public RevelanceManagerApp ReleManagerApp { get; set; } public RevelanceManagerApp ReleManagerApp { get; set; }
public User Get(string account) public User Get(string account)
{ {
return _unitWork.FindSingle<User>(u => u.Account == account); return Repository.FindSingle(u => u.Account == account);
} }
@ -26,20 +24,24 @@ namespace OpenAuth.App
/// </summary> /// </summary>
public GridData Load(QueryUserListReq request) public GridData Load(QueryUserListReq request)
{ {
if (request.page < 1) request.page = 1; //TODO:如果列表为空新增加一个用户后前端会传一个0过来奇怪
IEnumerable<User> users; IEnumerable<User> users;
int records = 0; int records = 0;
if (request.orgId ==string.Empty) if (string.IsNullOrEmpty(request.orgId))
{ {
users = _unitWork.Find<User>(null).OrderBy(u => u.Id).Skip((request.page - 1) * request.limit).Take(request.limit); users = UnitWork.Find<User>(null).OrderBy(u => u.Id).Skip((request.page - 1) * request.limit).Take(request.limit);
records = _unitWork.GetCount<User>(); records = UnitWork.GetCount<User>();
} }
else else
{ {
var ids = GetSubOrgIds(request.orgId); var ids = GetSubOrgIds(request.orgId);
users = _unitWork.Find<User>(u =>ids.Contains(u.Id)).OrderBy(u => u.Id).Skip((request.page - 1) * request.limit).Take(request.limit); List<string> userIds = ReleManagerApp.Get("UserOrg", false, ids);
records = _unitWork.GetCount<User>(); users = UnitWork.Find<User>(u =>userIds.Contains(u.Id))
.OrderBy(u => u.Name)
.Skip((request.page - 1) * request.limit)
.Take(request.limit);
records = UnitWork.GetCount<User>();
} }
var userviews = new List<UserView>(); var userviews = new List<UserView>();
foreach (var user in users) foreach (var user in users)
{ {
@ -62,14 +64,15 @@ namespace OpenAuth.App
/// </summary> /// </summary>
private string[] GetSubOrgIds(string orgId) private string[] GetSubOrgIds(string orgId)
{ {
var org = _unitWork.FindSingle<Org>(u => u.Id == orgId); var org = UnitWork.FindSingle<Org>(u => u.Id == orgId);
var orgs = _unitWork.Find<Org>(u => u.CascadeId.Contains(org.CascadeId)).Select(u => u.Id).ToArray(); var orgs = UnitWork.Find<Org>(u => u.CascadeId.Contains(org.CascadeId))
.Select(u => u.Id).ToArray();
return orgs; return orgs;
} }
public UserView Find(string id) public UserView Find(string id)
{ {
var user = _unitWork.FindSingle<User>(u => u.Id == id); var user = Repository.FindSingle(u => u.Id == id);
if (user == null) return new UserView(); if (user == null) return new UserView();
UserView view = user; UserView view = user;
@ -85,7 +88,7 @@ namespace OpenAuth.App
public void Delete(string[] ids) public void Delete(string[] ids)
{ {
_unitWork.Delete<User>(u => ids.Contains(u.Id)); Repository.Delete(u => ids.Contains(u.Id));
} }
public void AddOrUpdate(UserView view) public void AddOrUpdate(UserView view)
@ -95,19 +98,18 @@ namespace OpenAuth.App
User user = view; User user = view;
if (string.IsNullOrEmpty(view.Id)) if (string.IsNullOrEmpty(view.Id))
{ {
if (_unitWork.IsExist<User>(u => u.Account == view.Account)) if (UnitWork.IsExist<User>(u => u.Account == view.Account))
{ {
throw new Exception("用户账号已存在"); throw new Exception("用户账号已存在");
} }
user.CreateTime = DateTime.Now; user.CreateTime = DateTime.Now;
user.Password = user.Account; //初始密码与账号相同 user.Password = user.Account; //初始密码与账号相同
_unitWork.Add(user); Repository.Add(user);
_unitWork.Save();
view.Id = user.Id; //要把保存后的ID存入view view.Id = user.Id; //要把保存后的ID存入view
} }
else else
{ {
_unitWork.Update<User>(u => u.Id == view.Id, u => new User UnitWork.Update<User>(u => u.Id == view.Id, u => new User
{ {
Account = user.Account, Account = user.Account,
BizCode = user.BizCode, BizCode = user.BizCode,
@ -128,8 +130,8 @@ namespace OpenAuth.App
/// </summary> /// </summary>
public IEnumerable<Org> LoadByUser(string userId) public IEnumerable<Org> LoadByUser(string userId)
{ {
var result = from userorg in _unitWork.Find<Relevance>(null) var result = from userorg in UnitWork.Find<Relevance>(null)
join org in _unitWork.Find<Org>(null) on userorg.SecondId equals org.Id join org in UnitWork.Find<Org>(null) on userorg.SecondId equals org.Id
where userorg.FirstId == userId && userorg.Key == "UserOrg" where userorg.FirstId == userId && userorg.Key == "UserOrg"
select org; select org;
return result; return result;

View File

@ -29,11 +29,11 @@ namespace OpenAuth.Mvc.Controllers
try try
{ {
App.AddOrUpdate(view); App.AddOrUpdate(view);
} }
catch (Exception ex) catch (Exception ex)
{ {
Result.Code = 500; Result.Code = 500;
Result.Message = ex.Message; Result.Message = ex.Message;
} }
return JsonHelper.Instance.Serialize(Result); return JsonHelper.Instance.Serialize(Result);
@ -56,7 +56,7 @@ namespace OpenAuth.Mvc.Controllers
} }
catch (Exception e) catch (Exception e)
{ {
Result.Code = 500; Result.Code = 500;
Result.Message = e.Message; Result.Message = e.Message;
} }
@ -71,8 +71,8 @@ namespace OpenAuth.Mvc.Controllers
/// </summary> /// </summary>
public string GetAccessedUsers() public string GetAccessedUsers()
{ {
IEnumerable<UserView> users = App.Load(new QueryUserListReq()).data; IEnumerable<UserView> users = App.Load(new QueryUserListReq()).data;
var result = new Dictionary<string , object>(); var result = new Dictionary<string, object>();
foreach (var user in users) foreach (var user in users)
{ {
var item = new var item = new

View File

@ -48,8 +48,8 @@ namespace OpenAuth.UnitTest
{ {
var request = new QueryUserListReq var request = new QueryUserListReq
{ {
orgId = "990cb229-cc18-41f3-8e2b-13f0f0110798", orgId = "543a9fcf-4770-4fd9-865f-030e562be238",
page = 2, page = 1,
limit = 30 limit = 30
}; };
var users = _app.Load(request); var users = _app.Load(request);

View File

@ -27,12 +27,8 @@ namespace OpenAuth.WebApi.Areas.SSO.Controllers
/// </summary> /// </summary>
public class CheckController : ApiController public class CheckController : ApiController
{ {
private AuthorizeApp _app; public AuthorizeApp _app { get; set; }
private ObjCacheProvider<UserAuthSession> _objCacheProvider = new ObjCacheProvider<UserAuthSession>(); private ObjCacheProvider<UserAuthSession> _objCacheProvider = new ObjCacheProvider<UserAuthSession>();
public CheckController()
{
_app = AutofacExt.GetFromFac<AuthorizeApp>();
}
/// <summary> /// <summary>
/// 检验token是否有效 /// 检验token是否有效

View File

@ -11,12 +11,7 @@ namespace OpenAuth.WebApi.Areas.SSO.Controllers
/// </summary> /// </summary>
public class LoginController : Controller public class LoginController : Controller
{ {
private AppInfoService _appInfoService; public AppInfoService _appInfoService { get; set; }
public LoginController()
{
_appInfoService = new AppInfoService();
}
private const string AppInfo = "AppInfo"; private const string AppInfo = "AppInfo";

View File

@ -13,10 +13,11 @@
// *********************************************************************** // ***********************************************************************
using System.Reflection; using System.Reflection;
using System.Web.Http;
using System.Web.Mvc; using System.Web.Mvc;
using Autofac; using Autofac;
using Autofac.Configuration;
using Autofac.Integration.Mvc; using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using OpenAuth.App; using OpenAuth.App;
using OpenAuth.Domain.Interface; using OpenAuth.Domain.Interface;
using OpenAuth.Repository; using OpenAuth.Repository;
@ -50,8 +51,13 @@ namespace OpenAuth.WebApi
// OPTIONAL: Enable property injection into action filters. // OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider(); builder.RegisterFilterProvider();
// Set the dependency resolver to be Autofac. //注册所有的ApiControllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
var container = builder.Build(); var container = builder.Build();
HttpConfiguration config = GlobalConfiguration.Configuration;
//注册api容器需要使用HttpConfiguration对象
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
} }

View File

@ -57,6 +57,10 @@
<HintPath>..\packages\Autofac.Mvc5.3.3.4\lib\net45\Autofac.Integration.Mvc.dll</HintPath> <HintPath>..\packages\Autofac.Mvc5.3.3.4\lib\net45\Autofac.Integration.Mvc.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="Autofac.Integration.WebApi, Version=3.4.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<HintPath>..\packages\Autofac.WebApi2.3.4.0\lib\net45\Autofac.Integration.WebApi.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> <Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath> <HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private> <Private>True</Private>

View File

@ -4,6 +4,7 @@
<package id="Autofac" version="3.5.2" targetFramework="net45" /> <package id="Autofac" version="3.5.2" targetFramework="net45" />
<package id="Autofac.Configuration" version="3.3.0" targetFramework="net45" /> <package id="Autofac.Configuration" version="3.3.0" targetFramework="net45" />
<package id="Autofac.Mvc5" version="3.3.4" targetFramework="net45" /> <package id="Autofac.Mvc5" version="3.3.4" targetFramework="net45" />
<package id="Autofac.WebApi2" version="3.4.0" targetFramework="net45" />
<package id="bootstrap" version="3.0.0" targetFramework="net45" /> <package id="bootstrap" version="3.0.0" targetFramework="net45" />
<package id="EntityFramework" version="6.1.3" targetFramework="net45" /> <package id="EntityFramework" version="6.1.3" targetFramework="net45" />
<package id="jQuery" version="1.10.2" targetFramework="net45" /> <package id="jQuery" version="1.10.2" targetFramework="net45" />