1 完成用户部门权限分配处理,可以为用户分配可见部门,如果没有任何可见部门,则只能查看自己有关的数据;

2 完善进出库实例;
3 添加CodeSmith生成EF DbContext Entity Mapping;
This commit is contained in:
yubaolee
2016-01-07 11:47:43 +08:00
parent c2099cd337
commit f0b42e83d4
62 changed files with 5687 additions and 1592 deletions

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: 添加界面
Author: yubaolee
Description: 任务对象界面

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,816 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using CodeSmith.Engine;
using SchemaExplorer;
namespace SchemaMapper
{
public enum TableNaming
{
Mixed = 0,
Plural = 1,
Singular = 2
}
public enum EntityNaming
{
Preserve = 0,
Plural = 1,
Singular = 2
}
public enum RelationshipNaming
{
None = 0,
Plural = 1,
ListSuffix = 2
}
public enum ContextNaming
{
Preserve = 0,
Plural = 1,
TableSuffix = 2
}
public class GeneratorSettings
{
public GeneratorSettings()
{
RelationshipNaming = RelationshipNaming.ListSuffix;
EntityNaming = EntityNaming.Singular;
TableNaming = TableNaming.Singular;
CleanExpressions = new List<string> { @"^\d+" };
IgnoreExpressions = new List<string>();
}
public TableNaming TableNaming { get; set; }
public EntityNaming EntityNaming { get; set; }
public RelationshipNaming RelationshipNaming { get; set; }
public ContextNaming ContextNaming { get; set; }
public List<string> IgnoreExpressions { get; set; }
public List<string> CleanExpressions { get; set; }
public bool InclusionMode { get; set; }
public bool IsIgnored(string name)
{
if (IgnoreExpressions.Count == 0)
return false;
bool isMatch = IgnoreExpressions.Any(regex => Regex.IsMatch(name, regex));
return InclusionMode ? !isMatch : isMatch;
}
public string CleanName(string name)
{
if (CleanExpressions.Count == 0)
return name;
foreach (var regex in CleanExpressions.Where(r => !string.IsNullOrEmpty(r)))
if (Regex.IsMatch(name, regex))
return Regex.Replace(name, regex, "");
return name;
}
public string RelationshipName(string name)
{
if (RelationshipNaming == RelationshipNaming.None)
return name;
if (RelationshipNaming == RelationshipNaming.ListSuffix)
return name + "List";
return StringUtil.ToPascalCase(StringUtil.ToPlural(name));
}
public string ContextName(string name)
{
if (ContextNaming == ContextNaming.Preserve)
return name;
if (ContextNaming == ContextNaming.TableSuffix)
return name + "Table";
return StringUtil.ToPascalCase(StringUtil.ToPlural(name));
}
public string EntityName(string name)
{
if (TableNaming != TableNaming.Plural && EntityNaming == EntityNaming.Plural)
name = StringUtil.ToPlural(name);
else if (TableNaming != TableNaming.Singular && EntityNaming == EntityNaming.Singular)
name = StringUtil.ToSingular(name);
return StringUtil.ToPascalCase(name);
}
}
public class SchemaItemProcessedEventArgs : EventArgs
{
public SchemaItemProcessedEventArgs(string name)
{
_name = name;
}
private readonly string _name;
public string Name
{
get { return _name; }
}
}
public class UniqueNamer
{
private readonly ConcurrentDictionary<string, HashSet<string>> _names;
public UniqueNamer()
{
_names = new ConcurrentDictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
Comparer = StringComparer.CurrentCulture;
// add existing
UniqueContextName("ChangeTracker");
UniqueContextName("Configuration");
UniqueContextName("Database");
UniqueContextName("InternalContext");
}
public IEqualityComparer<string> Comparer { get; set; }
public string UniqueName(string bucketName, string name)
{
var hashSet = _names.GetOrAdd(bucketName, k => new HashSet<string>(Comparer));
string result = name.MakeUnique(hashSet.Contains);
hashSet.Add(result);
return result;
}
public string UniqueClassName(string className)
{
const string globalClassName = "global::ClassName";
return UniqueName(globalClassName, className);
}
public string UniqueContextName(string name)
{
const string globalContextname = "global::ContextName";
return UniqueName(globalContextname, name);
}
public string UniqueRelationshipName(string name)
{
const string globalContextname = "global::RelationshipName";
return UniqueName(globalContextname, name);
}
}
public class Generator
{
private readonly UniqueNamer _namer;
public Generator()
{
_settings = new GeneratorSettings();
_namer = new UniqueNamer();
}
public event EventHandler<SchemaItemProcessedEventArgs> SchemaItemProcessed;
protected void OnSchemaItemProcessed(string name)
{
var handler = SchemaItemProcessed;
if (handler == null)
return;
handler(this, new SchemaItemProcessedEventArgs(name));
}
private readonly GeneratorSettings _settings;
public GeneratorSettings Settings
{
get { return _settings; }
}
public EntityContext Generate(DatabaseSchema databaseSchema)
{
// only DeepLoad when in ignore mode
databaseSchema.DeepLoad = !Settings.InclusionMode;
var entityContext = new EntityContext();
entityContext.DatabaseName = databaseSchema.Name;
string dataContextName = StringUtil.ToPascalCase(databaseSchema.Name) + "Context";
dataContextName = _namer.UniqueClassName(dataContextName);
entityContext.ClassName = dataContextName;
foreach (TableSchema t in databaseSchema.Tables)
{
if (Settings.IsIgnored(t.FullName))
{
Debug.WriteLine("Skipping Table: " + t.FullName);
}
else if (IsManyToMany(t))
{
CreateManyToMany(entityContext, t);
}
else
{
Debug.WriteLine("Getting Table Schema: " + t.FullName);
GetEntity(entityContext, t);
}
OnSchemaItemProcessed(t.FullName);
}
return entityContext;
}
private Entity GetEntity(EntityContext entityContext, TableSchema tableSchema, bool processRelationships = true, bool processMethods = true)
{
string key = tableSchema.FullName;
Entity entity = entityContext.Entities.ByTable(key)
?? CreateEntity(entityContext, tableSchema);
if (!entity.Properties.IsProcessed)
CreateProperties(entity, tableSchema);
if (processRelationships && !entity.Relationships.IsProcessed)
CreateRelationships(entityContext, entity, tableSchema);
if (processMethods && !entity.Methods.IsProcessed)
CreateMethods(entity, tableSchema);
entity.IsProcessed = true;
return entity;
}
private Entity CreateEntity(EntityContext entityContext, TableSchema tableSchema)
{
var entity = new Entity
{
FullName = tableSchema.FullName,
TableName = tableSchema.Name,
TableSchema = tableSchema.Owner,
Description = tableSchema.Description
};
string className = ToClassName(tableSchema.Name);
className = _namer.UniqueClassName(className);
string mappingName = className + "Map";
mappingName = _namer.UniqueClassName(mappingName);
string contextName = Settings.ContextName(className);
contextName = ToPropertyName(entityContext.ClassName, contextName);
contextName = _namer.UniqueContextName(contextName);
entity.ClassName = className;
entity.ContextName = contextName;
entity.MappingName = mappingName;
entityContext.Entities.Add(entity);
return entity;
}
/// <summary>
/// 创建实体的属性
/// </summary>
private void CreateProperties(Entity entity, TableSchema tableSchema)
{
foreach (ColumnSchema columnSchema in tableSchema.Columns)
{
// skip unsupported type
if (columnSchema.NativeType.Equals("hierarchyid", StringComparison.OrdinalIgnoreCase)
|| columnSchema.NativeType.Equals("sql_variant", StringComparison.OrdinalIgnoreCase))
{
Debug.WriteLine(string.Format("Skipping column '{0}' because it has an unsupported db type '{1}'.",
columnSchema.Name, columnSchema.NativeType));
continue;
}
Property property = entity.Properties.ByColumn(columnSchema.Name);
if (property == null)
{
property = new Property { ColumnName = columnSchema.Name };
entity.Properties.Add(property);
}
string propertyName = ToPropertyName(entity.ClassName, columnSchema.Name);
propertyName = _namer.UniqueName(entity.ClassName, propertyName);
property.PropertyName = propertyName;
property.DataType = columnSchema.DataType;
property.SystemType = columnSchema.SystemType;
property.NativeType = columnSchema.NativeType;
property.Description = columnSchema.Description;
property.IsPrimaryKey = columnSchema.IsPrimaryKeyMember;
property.IsForeignKey = columnSchema.IsForeignKeyMember;
property.IsNullable = columnSchema.AllowDBNull;
property.IsIdentity = IsIdentity(columnSchema);
property.IsRowVersion = IsRowVersion(columnSchema);
property.IsAutoGenerated = IsDbGenerated(columnSchema);
if (columnSchema.IsUnique)
property.IsUnique = columnSchema.IsUnique;
if (property.SystemType == typeof(string)
|| property.SystemType == typeof(byte[]))
{
property.MaxLength = columnSchema.Size;
}
if (property.SystemType == typeof(float)
|| property.SystemType == typeof(double)
|| property.SystemType == typeof(decimal))
{
property.Precision = columnSchema.Precision;
property.Scale = columnSchema.Scale;
}
property.IsProcessed = true;
}
entity.Properties.IsProcessed = true;
}
private void CreateRelationships(EntityContext entityContext, Entity entity, TableSchema tableSchema)
{
foreach (TableKeySchema tableKey in tableSchema.ForeignKeys)
{
if (Settings.IsIgnored(tableKey.ForeignKeyTable.FullName)
|| Settings.IsIgnored(tableKey.PrimaryKeyTable.FullName))
{
Debug.WriteLine("Skipping relationship '{0}' because table '{1}' or '{2}' is ignored.",
tableKey.FullName, tableKey.ForeignKeyTable.FullName, tableKey.PrimaryKeyTable.FullName);
continue;
}
CreateRelationship(entityContext, entity, tableKey);
}
entity.Relationships.IsProcessed = true;
}
private void CreateRelationship(EntityContext entityContext, Entity foreignEntity, TableKeySchema tableKeySchema)
{
Entity primaryEntity = GetEntity(entityContext, tableKeySchema.PrimaryKeyTable, false, false);
string primaryName = primaryEntity.ClassName;
string foreignName = foreignEntity.ClassName;
string relationshipName = tableKeySchema.Name;
relationshipName = _namer.UniqueRelationshipName(relationshipName);
bool isCascadeDelete = IsCascadeDelete(tableKeySchema);
bool foreignMembersRequired;
bool primaryMembersRequired;
var foreignMembers = GetKeyMembers(foreignEntity, tableKeySchema.ForeignKeyMemberColumns, tableKeySchema.Name, out foreignMembersRequired);
var primaryMembers = GetKeyMembers(primaryEntity, tableKeySchema.PrimaryKeyMemberColumns, tableKeySchema.Name, out primaryMembersRequired);
Relationship foreignRelationship = foreignEntity.Relationships
.FirstOrDefault(r => r.RelationshipName == relationshipName && r.IsForeignKey);
if (foreignRelationship == null)
{
foreignRelationship = new Relationship { RelationshipName = relationshipName };
foreignEntity.Relationships.Add(foreignRelationship);
}
foreignRelationship.IsMapped = true;
foreignRelationship.IsForeignKey = true;
foreignRelationship.ThisCardinality = foreignMembersRequired ? Cardinality.One : Cardinality.ZeroOrOne;
foreignRelationship.ThisEntity = foreignName;
foreignRelationship.ThisProperties = new List<string>(foreignMembers);
foreignRelationship.OtherEntity = primaryName;
foreignRelationship.OtherProperties = new List<string>(primaryMembers);
foreignRelationship.CascadeDelete = isCascadeDelete;
string prefix = GetMemberPrefix(foreignRelationship, primaryName, foreignName);
string foreignPropertyName = ToPropertyName(foreignEntity.ClassName, prefix + primaryName);
foreignPropertyName = _namer.UniqueName(foreignEntity.ClassName, foreignPropertyName);
foreignRelationship.ThisPropertyName = foreignPropertyName;
// add reverse
Relationship primaryRelationship = primaryEntity.Relationships
.FirstOrDefault(r => r.RelationshipName == relationshipName && r.IsForeignKey == false);
if (primaryRelationship == null)
{
primaryRelationship = new Relationship { RelationshipName = relationshipName };
primaryEntity.Relationships.Add(primaryRelationship);
}
primaryRelationship.IsMapped = false;
primaryRelationship.IsForeignKey = false;
primaryRelationship.ThisEntity = primaryName;
primaryRelationship.ThisProperties = new List<string>(primaryMembers);
primaryRelationship.OtherEntity = foreignName;
primaryRelationship.OtherProperties = new List<string>(foreignMembers);
primaryRelationship.CascadeDelete = isCascadeDelete;
bool isOneToOne = IsOneToOne(tableKeySchema, foreignRelationship);
if (isOneToOne)
primaryRelationship.ThisCardinality = primaryMembersRequired ? Cardinality.One : Cardinality.ZeroOrOne;
else
primaryRelationship.ThisCardinality = Cardinality.Many;
string primaryPropertyName = prefix + foreignName;
if (!isOneToOne)
primaryPropertyName = Settings.RelationshipName(primaryPropertyName);
primaryPropertyName = ToPropertyName(primaryEntity.ClassName, primaryPropertyName);
primaryPropertyName = _namer.UniqueName(primaryEntity.ClassName, primaryPropertyName);
primaryRelationship.ThisPropertyName = primaryPropertyName;
foreignRelationship.OtherPropertyName = primaryRelationship.ThisPropertyName;
foreignRelationship.OtherCardinality = primaryRelationship.ThisCardinality;
primaryRelationship.OtherPropertyName = foreignRelationship.ThisPropertyName;
primaryRelationship.OtherCardinality = foreignRelationship.ThisCardinality;
foreignRelationship.IsProcessed = true;
primaryRelationship.IsProcessed = true;
}
private void CreateManyToMany(EntityContext entityContext, TableSchema joinTable)
{
if (joinTable.ForeignKeys.Count != 2)
return;
var joinTableName = joinTable.Name;
var joinSchemaName = joinTable.Owner;
// first fkey is always left, second fkey is right
var leftForeignKey = joinTable.ForeignKeys[0];
var leftTable = leftForeignKey.PrimaryKeyTable;
var joinLeftColumn = leftForeignKey.ForeignKeyMemberColumns.Select(c => c.Name).ToList();
var leftEntity = GetEntity(entityContext, leftTable, false, false);
var rightForeignKey = joinTable.ForeignKeys[1];
var rightTable = rightForeignKey.PrimaryKeyTable;
var joinRightColumn = rightForeignKey.ForeignKeyMemberColumns.Select(c => c.Name).ToList();
var rightEntity = GetEntity(entityContext, rightTable, false, false);
string leftPropertyName = Settings.RelationshipName(rightEntity.ClassName);
leftPropertyName = _namer.UniqueName(leftEntity.ClassName, leftPropertyName);
string rightPropertyName = Settings.RelationshipName(leftEntity.ClassName);
rightPropertyName = _namer.UniqueName(rightEntity.ClassName, rightPropertyName);
string relationshipName = string.Format("{0}|{1}",
leftForeignKey.Name,
rightForeignKey.Name);
relationshipName = _namer.UniqueRelationshipName(relationshipName);
var left = new Relationship { RelationshipName = relationshipName };
left.IsForeignKey = false;
left.IsMapped = true;
left.ThisCardinality = Cardinality.Many;
left.ThisEntity = leftEntity.ClassName;
left.ThisPropertyName = leftPropertyName;
left.OtherCardinality = Cardinality.Many;
left.OtherEntity = rightEntity.ClassName;
left.OtherPropertyName = rightPropertyName;
left.JoinTable = joinTableName;
left.JoinSchema = joinSchemaName;
left.JoinThisColumn = new List<string>(joinLeftColumn);
left.JoinOtherColumn = new List<string>(joinRightColumn);
leftEntity.Relationships.Add(left);
var right = new Relationship { RelationshipName = relationshipName };
right.IsForeignKey = false;
right.IsMapped = false;
right.ThisCardinality = Cardinality.Many;
right.ThisEntity = rightEntity.ClassName;
right.ThisPropertyName = rightPropertyName;
right.OtherCardinality = Cardinality.Many;
right.OtherEntity = leftEntity.ClassName;
right.OtherPropertyName = leftPropertyName;
right.JoinTable = joinTableName;
right.JoinSchema = joinSchemaName;
right.JoinThisColumn = new List<string>(joinRightColumn);
right.JoinOtherColumn = new List<string>(joinLeftColumn);
rightEntity.Relationships.Add(right);
}
private void CreateMethods(Entity entity, TableSchema tableSchema)
{
if (tableSchema.HasPrimaryKey)
{
var method = GetMethodFromColumns(entity, tableSchema.PrimaryKey.MemberColumns);
if (method != null)
{
method.IsKey = true;
method.SourceName = tableSchema.PrimaryKey.FullName;
if (!entity.Methods.Any(m => m.NameSuffix == method.NameSuffix))
entity.Methods.Add(method);
}
}
GetIndexMethods(entity, tableSchema);
GetForeignKeyMethods(entity, tableSchema);
entity.Methods.IsProcessed = true;
}
private static void GetForeignKeyMethods(Entity entity, TableSchema table)
{
var columns = new List<ColumnSchema>();
foreach (ColumnSchema column in table.ForeignKeyColumns)
{
columns.Add(column);
Method method = GetMethodFromColumns(entity, columns);
if (method != null && !entity.Methods.Any(m => m.NameSuffix == method.NameSuffix))
entity.Methods.Add(method);
columns.Clear();
}
}
private static void GetIndexMethods(Entity entity, TableSchema table)
{
foreach (IndexSchema index in table.Indexes)
{
Method method = GetMethodFromColumns(entity, index.MemberColumns);
if (method == null)
continue;
method.SourceName = index.FullName;
method.IsUnique = index.IsUnique;
method.IsIndex = true;
if (!entity.Methods.Any(m => m.NameSuffix == method.NameSuffix))
entity.Methods.Add(method);
}
}
private static Method GetMethodFromColumns(Entity entity, IEnumerable<ColumnSchema> columns)
{
var method = new Method();
string methodName = string.Empty;
foreach (var column in columns)
{
var property = entity.Properties.ByColumn(column.Name);
if (property == null)
continue;
method.Properties.Add(property);
methodName += property.PropertyName;
}
if (method.Properties.Count == 0)
return null;
method.NameSuffix = methodName;
return method;
}
private static List<string> GetKeyMembers(Entity entity, IEnumerable<MemberColumnSchema> members, string name, out bool isRequired)
{
var keyMembers = new List<string>();
isRequired = false;
foreach (var member in members)
{
var property = entity.Properties.ByColumn(member.Name);
if (property == null)
throw new InvalidOperationException(string.Format(
"Could not find column {0} for relationship {1}.",
member.Name,
name));
if (!isRequired)
isRequired = property.IsRequired;
keyMembers.Add(property.PropertyName);
}
return keyMembers;
}
private static string GetMemberPrefix(Relationship relationship, string primaryClass, string foreignClass)
{
string thisKey = relationship.ThisProperties.FirstOrDefault() ?? string.Empty;
string otherKey = relationship.OtherProperties.FirstOrDefault() ?? string.Empty;
bool isSameName = thisKey.Equals(otherKey, StringComparison.OrdinalIgnoreCase);
isSameName = (isSameName || thisKey.Equals(primaryClass + otherKey, StringComparison.OrdinalIgnoreCase));
string prefix = string.Empty;
if (isSameName)
return prefix;
prefix = thisKey.Replace(otherKey, "");
prefix = prefix.Replace(primaryClass, "");
prefix = prefix.Replace(foreignClass, "");
prefix = Regex.Replace(prefix, @"(_ID|_id|_Id|\.ID|\.id|\.Id|ID|Id)$", "");
prefix = Regex.Replace(prefix, @"^\d", "");
return prefix;
}
private static bool IsOneToOne(TableKeySchema tableKeySchema, Relationship foreignRelationship)
{
bool isFkeyPkey = tableKeySchema.ForeignKeyTable.HasPrimaryKey
&& tableKeySchema.ForeignKeyTable.PrimaryKey != null
&& tableKeySchema.ForeignKeyTable.PrimaryKey.MemberColumns.Count == 1
&& tableKeySchema.ForeignKeyTable.PrimaryKey.MemberColumns.Contains(
foreignRelationship.ThisProperties.FirstOrDefault());
if (isFkeyPkey)
return true;
// if f.key is unique
return tableKeySchema.ForeignKeyMemberColumns.All(column => column.IsUnique);
}
private static bool IsManyToMany(TableSchema tableSchema)
{
// 1) Table must have Two ForeignKeys.
// 2) All columns must be either...
// a) Member of a Foreign Key.
// b) DbGenerated
if (tableSchema.Columns.Count < 2)
return false;
if (tableSchema.ForeignKeyColumns.Count != 2)
return false;
// all columns are fkeys
if (tableSchema.Columns.Count == 2 &&
tableSchema.ForeignKeyColumns.Count == 2)
return true;
// check all non fkey columns to make sure db gen'd
return tableSchema.NonForeignKeyColumns.All(c =>
IsDbGenerated(c) || HasDefaultValue(c));
}
#region Name Helpers
private string ToClassName(string name)
{
name = Settings.EntityName(name);
string legalName = ToLegalName(name);
return legalName;
}
private string ToPropertyName(string className, string name)
{
string propertyName = ToLegalName(name);
if (className.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
propertyName += "Member";
return propertyName;
}
private string ToLegalName(string name)
{
string legalName = Settings.CleanName(name);
legalName = StringUtil.ToPascalCase(legalName);
return legalName;
}
#endregion
#region Column Flag Helpers
private static bool IsCascadeDelete(SchemaObjectBase column)
{
bool cascadeDelete = false;
string value;
try
{
if (column.ExtendedProperties.Contains(ExtendedPropertyNames.CascadeDelete))
{
value = column.ExtendedProperties[ExtendedPropertyNames.CascadeDelete].Value.ToString();
bool.TryParse(value, out cascadeDelete);
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return cascadeDelete;
}
private static bool IsRowVersion(DataObjectBase column)
{
bool isTimeStamp = column.NativeType.Equals(
"timestamp", StringComparison.OrdinalIgnoreCase);
bool isRowVersion = column.NativeType.Equals(
"rowversion", StringComparison.OrdinalIgnoreCase);
return (isTimeStamp || isRowVersion);
}
private static bool IsDbGenerated(DataObjectBase column)
{
if (IsRowVersion(column))
return true;
if (IsIdentity(column))
return true;
bool isComputed = false;
string value;
try
{
if (column.ExtendedProperties.Contains(ExtendedPropertyNames.IsComputed))
{
value = column.ExtendedProperties[ExtendedPropertyNames.IsComputed].Value.ToString();
bool.TryParse(value, out isComputed);
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return isComputed;
}
private static bool IsIdentity(DataObjectBase column)
{
string temp;
bool isIdentity = false;
try
{
if (column.ExtendedProperties.Contains(ExtendedPropertyNames.IsIdentity))
{
temp = column.ExtendedProperties[ExtendedPropertyNames.IsIdentity].Value.ToString();
bool.TryParse(temp, out isIdentity);
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return isIdentity;
}
private static bool HasDefaultValue(DataObjectBase column)
{
try
{
if (!column.ExtendedProperties.Contains(ExtendedPropertyNames.DefaultValue))
return false;
string value = column.ExtendedProperties[ExtendedPropertyNames.DefaultValue].Value.ToString();
return !string.IsNullOrEmpty(value);
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
}
return false;
}
#endregion
}
}

View File

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

View File

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

View File

@@ -0,0 +1,639 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp;
namespace SchemaMapper
{
#region Mapping Parser
[DebuggerDisplay("Table: {TableName}, Entity: {EntityClass}, Mapping: {MappingClass}")]
public class ParsedEntity
{
public ParsedEntity()
{
Properties = new List<ParsedProperty>();
Relationships = new List<ParsedRelationship>();
}
public string EntityClass { get; set; }
public string MappingClass { get; set; }
public string TableName { get; set; }
public string TableSchema { get; set; }
public List<ParsedProperty> Properties { get; private set; }
public List<ParsedRelationship> Relationships { get; private set; }
}
[DebuggerDisplay("Column: {ColumnName}, Property: {PropertyName}")]
public class ParsedProperty
{
public string ColumnName { get; set; }
public string PropertyName { get; set; }
}
[DebuggerDisplay("This: {ThisPropertyName}, Other: {OtherPropertyName}")]
public class ParsedRelationship
{
public ParsedRelationship()
{
ThisProperties = new List<string>();
JoinThisColumn = new List<string>();
JoinOtherColumn = new List<string>();
}
public string ThisPropertyName { get; set; }
public List<string> ThisProperties { get; private set; }
public string OtherPropertyName { get; set; }
public string JoinTable { get; set; }
public string JoinSchema { get; set; }
public List<string> JoinThisColumn { get; private set; }
public List<string> JoinOtherColumn { get; private set; }
}
public class MappingVisitor : DepthFirstAstVisitor<object, object>
{
public MappingVisitor()
{
MappingBaseType = "EntityTypeConfiguration";
}
public string MappingBaseType { get; set; }
public ParsedEntity ParsedEntity { get; set; }
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
var baseType = typeDeclaration.BaseTypes.OfType<MemberType>().FirstOrDefault();
if (baseType == null || baseType.MemberName != MappingBaseType)
return base.VisitTypeDeclaration(typeDeclaration, data);
var entity = baseType.TypeArguments.OfType<MemberType>().FirstOrDefault();
if (entity == null)
return base.VisitTypeDeclaration(typeDeclaration, data);
if (ParsedEntity == null)
ParsedEntity = new ParsedEntity();
ParsedEntity.EntityClass = entity.MemberName;
ParsedEntity.MappingClass = typeDeclaration.Name;
return base.VisitTypeDeclaration(typeDeclaration, ParsedEntity);
}
public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
{
if (data == null)
return base.VisitInvocationExpression(invocationExpression, null);
// visit all the methods
var identifier = invocationExpression.Target.Children.OfType<Identifier>().FirstOrDefault();
string methodName = identifier == null ? string.Empty : identifier.Name;
// the different types of incoming data, helps us know what we're parsing
var parsedEntity = data as ParsedEntity;
var parsedProperty = data as ParsedProperty;
var parsedRelationship = data as ParsedRelationship;
switch (methodName)
{
case "ToTable":
var tableNameExpression = invocationExpression.Arguments
.OfType<PrimitiveExpression>()
.ToArray();
string tableName = null;
string tableSchema = null;
if (tableNameExpression.Length >= 1)
tableName = tableNameExpression[0].Value.ToString();
if (tableNameExpression.Length >= 2)
tableSchema = tableNameExpression[1].Value.ToString();
// ToTable is either Entity -> Table map or Many to Many map
if (parsedEntity != null)
{
// when data is ParsedEntity, entity map
parsedEntity.TableName = tableName;
parsedEntity.TableSchema = tableSchema;
}
else if (parsedRelationship != null)
{
// when data is ParsedRelationship, many to many map
parsedRelationship.JoinTable = tableName;
parsedRelationship.JoinSchema = tableSchema;
}
break;
case "HasColumnName":
var columnNameExpression = invocationExpression.Arguments
.OfType<PrimitiveExpression>()
.FirstOrDefault();
if (columnNameExpression == null)
break;
// property to column map start.
string columnName = columnNameExpression.Value.ToString();
var property = new ParsedProperty { ColumnName = columnName };
ParsedEntity.Properties.Add(property);
//only have column info at this point. pass data to get property name.
return base.VisitInvocationExpression(invocationExpression, property);
case "Property":
var propertyExpression = invocationExpression.Arguments
.OfType<LambdaExpression>()
.FirstOrDefault();
if (parsedProperty == null || propertyExpression == null)
break;
// ParsedProperty is passed in as data from HasColumnName, add property name
var propertyBodyExpression = propertyExpression.Body as MemberReferenceExpression;
if (propertyBodyExpression != null)
parsedProperty.PropertyName = propertyBodyExpression.MemberName;
break;
case "Map":
// start a new Many to Many relationship
var mapRelation = new ParsedRelationship();
ParsedEntity.Relationships.Add(mapRelation);
// pass to child nodes to fill in data
return base.VisitInvocationExpression(invocationExpression, mapRelation);
case "HasForeignKey":
var foreignExpression = invocationExpression.Arguments
.OfType<LambdaExpression>()
.FirstOrDefault();
if (foreignExpression == null)
break;
// when only 1 fkey, body will be member ref
if (foreignExpression.Body is MemberReferenceExpression)
{
var foreignBodyExpression = foreignExpression.Body as MemberReferenceExpression;
// start a new relationship
var foreignRelation = new ParsedRelationship();
ParsedEntity.Relationships.Add(foreignRelation);
foreignRelation.ThisProperties.Add(foreignBodyExpression.MemberName);
// pass as data for child nodes to fill in data
return base.VisitInvocationExpression(invocationExpression, foreignRelation);
}
// when more then 1 fkey, body will be an anonymous type
if (foreignExpression.Body is AnonymousTypeCreateExpression)
{
var foreignBodyExpression = foreignExpression.Body as AnonymousTypeCreateExpression;
var foreignRelation = new ParsedRelationship();
ParsedEntity.Relationships.Add(foreignRelation);
var properties = foreignBodyExpression.Children
.OfType<MemberReferenceExpression>()
.Select(m => m.MemberName);
foreignRelation.ThisProperties.AddRange(properties);
return base.VisitInvocationExpression(invocationExpression, foreignRelation);
}
break;
case "HasMany":
var hasManyExpression = invocationExpression.Arguments
.OfType<LambdaExpression>()
.FirstOrDefault();
if (parsedRelationship == null || hasManyExpression == null)
break;
// filling existing relationship data
var hasManyBodyExpression = hasManyExpression.Body as MemberReferenceExpression;
if (hasManyBodyExpression != null)
parsedRelationship.ThisPropertyName = hasManyBodyExpression.MemberName;
break;
case "WithMany":
var withManyExpression = invocationExpression.Arguments
.OfType<LambdaExpression>()
.FirstOrDefault();
if (parsedRelationship == null || withManyExpression == null)
break;
// filling existing relationship data
var withManyBodyExpression = withManyExpression.Body as MemberReferenceExpression;
if (withManyBodyExpression != null)
parsedRelationship.OtherPropertyName = withManyBodyExpression.MemberName;
break;
case "HasRequired":
case "HasOptional":
var hasExpression = invocationExpression.Arguments
.OfType<LambdaExpression>()
.FirstOrDefault();
if (parsedRelationship == null || hasExpression == null)
break;
// filling existing relationship data
var hasBodyExpression = hasExpression.Body as MemberReferenceExpression;
if (hasBodyExpression != null)
parsedRelationship.ThisPropertyName = hasBodyExpression.MemberName;
break;
case "MapLeftKey":
if (parsedRelationship == null)
break;
var leftKeyExpression = invocationExpression.Arguments
.OfType<PrimitiveExpression>()
.Select(e => e.Value.ToString());
parsedRelationship.JoinThisColumn.AddRange(leftKeyExpression);
break;
case "MapRightKey":
if (parsedRelationship == null)
break;
var rightKeyExpression = invocationExpression.Arguments
.OfType<PrimitiveExpression>()
.Select(e => e.Value.ToString());
parsedRelationship.JoinOtherColumn.AddRange(rightKeyExpression);
break;
}
return base.VisitInvocationExpression(invocationExpression, data);
}
}
public static class MappingParser
{
public static ParsedEntity Parse(string mappingFile)
{
if (string.IsNullOrEmpty(mappingFile) || !File.Exists(mappingFile))
return null;
var parser = new CSharpParser();
CompilationUnit compilationUnit;
using (var stream = File.OpenText(mappingFile))
compilationUnit = parser.Parse(stream, mappingFile);
var visitor = new MappingVisitor();
visitor.VisitCompilationUnit(compilationUnit, null);
var parsedEntity = visitor.ParsedEntity;
if (parsedEntity != null)
Debug.WriteLine("Parsed Mapping File: '{0}'; Properties: {1}; Relationships: {2}",
Path.GetFileName(mappingFile),
parsedEntity.Properties.Count,
parsedEntity.Relationships.Count);
return parsedEntity;
}
}
#endregion
#region Context Parser
[DebuggerDisplay("Context: {ContextClass}")]
public class ParsedContext
{
public ParsedContext()
{
Properties = new List<ParsedEntitySet>();
}
public string ContextClass { get; set; }
public List<ParsedEntitySet> Properties { get; private set; }
}
[DebuggerDisplay("Entity: {EntityClass}, Property: {ContextProperty}")]
public class ParsedEntitySet
{
public string EntityClass { get; set; }
public string ContextProperty { get; set; }
}
public class ContextVisitor : DepthFirstAstVisitor<object, object>
{
public ContextVisitor()
{
ContextBaseType = "DbContext";
DataSetType = "DbSet";
}
public string ContextBaseType { get; set; }
public string DataSetType { get; set; }
public ParsedContext ParsedContext { get; set; }
public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
var baseType = typeDeclaration.BaseTypes
.OfType<MemberType>()
.FirstOrDefault();
// warning: if inherited from custom base type, this will break
// anyway to improve this?
if (baseType == null || baseType.MemberName != ContextBaseType)
return base.VisitTypeDeclaration(typeDeclaration, data);
if (ParsedContext == null)
ParsedContext = new ParsedContext();
ParsedContext.ContextClass = typeDeclaration.Name;
return base.VisitTypeDeclaration(typeDeclaration, ParsedContext);
}
public override object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data)
{
if (data == null)
return base.VisitPropertyDeclaration(propertyDeclaration, null);
// look for property to return generic DbSet type
var memberType = propertyDeclaration.ReturnType as MemberType;
if (memberType == null || memberType.MemberName != DataSetType)
return base.VisitPropertyDeclaration(propertyDeclaration, data);
// get the first generic type
var entityType = memberType.TypeArguments
.OfType<MemberType>()
.FirstOrDefault();
if (entityType == null)
return base.VisitPropertyDeclaration(propertyDeclaration, data);
var entitySet = new ParsedEntitySet
{
EntityClass = entityType.MemberName,
ContextProperty = propertyDeclaration.Name
};
ParsedContext.Properties.Add(entitySet);
return base.VisitPropertyDeclaration(propertyDeclaration, data);
}
}
public static class ContextParser
{
public static ParsedContext Parse(string contextFile)
{
if (string.IsNullOrEmpty(contextFile) || !File.Exists(contextFile))
return null;
var parser = new CSharpParser();
CompilationUnit compilationUnit;
using (var stream = File.OpenText(contextFile))
compilationUnit = parser.Parse(stream, contextFile);
var visitor = new ContextVisitor();
visitor.VisitCompilationUnit(compilationUnit, null);
var parsedContext = visitor.ParsedContext;
if (parsedContext != null)
Debug.WriteLine("Parsed Context File: '{0}'; Entities: {1}",
Path.GetFileName(contextFile),
parsedContext.Properties.Count);
return parsedContext;
}
}
#endregion
public static class Synchronizer
{
public static bool UpdateFromSource(EntityContext generatedContext, string contextDirectory, string mappingDirectory)
{
if (generatedContext == null)
return false;
// make sure to update the entities before the context
UpdateFromMapping(generatedContext, mappingDirectory);
UpdateFromContext(generatedContext, contextDirectory);
return true;
}
private static void UpdateFromContext(EntityContext generatedContext, string contextDirectory)
{
if (generatedContext == null
|| contextDirectory == null
|| !Directory.Exists(contextDirectory))
return;
// parse context
ParsedContext parsedContext = null;
var files = Directory.EnumerateFiles(contextDirectory, "*.Generated.cs").GetEnumerator();
while (files.MoveNext() && parsedContext == null)
parsedContext = ContextParser.Parse(files.Current);
if (parsedContext == null)
return;
if (generatedContext.ClassName != parsedContext.ContextClass)
{
Debug.WriteLine("Rename Context Class'{0}' to '{1}'.",
generatedContext.ClassName,
parsedContext.ContextClass);
generatedContext.ClassName = parsedContext.ContextClass;
}
foreach (var parsedProperty in parsedContext.Properties)
{
var entity = generatedContext.Entities.ByClass(parsedProperty.EntityClass);
if (entity == null)
continue;
if (entity.ContextName == parsedProperty.ContextProperty)
continue;
Debug.WriteLine("Rename Context Property'{0}' to '{1}'.",
entity.ContextName,
parsedProperty.ContextProperty);
entity.ContextName = parsedProperty.ContextProperty;
}
}
private static void UpdateFromMapping(EntityContext generatedContext, string mappingDirectory)
{
if (generatedContext == null
|| mappingDirectory == null
|| !Directory.Exists(mappingDirectory))
return;
// parse all mapping files
var mappingFiles = Directory.EnumerateFiles(mappingDirectory, "*.Generated.cs");
var parsedEntities = mappingFiles
.Select(MappingParser.Parse)
.Where(parsedEntity => parsedEntity != null)
.ToList();
var relationshipQueue = new List<Tuple<Entity, ParsedEntity>>();
// update all entity and property names first because relationships are linked by property names
foreach (var parsedEntity in parsedEntities)
{
// find entity by table name to support renaming entity
var entity = generatedContext.Entities
.ByTable(parsedEntity.TableName, parsedEntity.TableSchema);
if (entity == null)
continue;
// sync names
if (entity.MappingName != parsedEntity.MappingClass)
{
Debug.WriteLine("Rename Mapping Class'{0}' to '{1}'.",
entity.MappingName,
parsedEntity.MappingClass);
entity.MappingName = parsedEntity.MappingClass;
}
// use rename api to make sure all instances are renamed
generatedContext.RenameEntity(entity.ClassName, parsedEntity.EntityClass);
// sync properties
foreach (var parsedProperty in parsedEntity.Properties)
{
// find property by column name to support property name rename
var property = entity.Properties.ByColumn(parsedProperty.ColumnName);
if (property == null)
continue;
// use rename api to make sure all instances are renamed
generatedContext.RenameProperty(
entity.ClassName,
property.PropertyName,
parsedProperty.PropertyName);
}
// save relationship for later processing
var item = new Tuple<Entity, ParsedEntity>(entity, parsedEntity);
relationshipQueue.Add(item);
}
// update relationships last
foreach (var tuple in relationshipQueue)
UpdateRelationships(generatedContext, tuple.Item1, tuple.Item2);
}
private static void UpdateRelationships(EntityContext generatedContext, Entity entity, ParsedEntity parsedEntity)
{
// sync relationships
foreach (var parsedRelationship in parsedEntity.Relationships.Where(r => r.JoinTable == null))
{
var parsedProperties = parsedRelationship.ThisProperties;
var relationship = entity.Relationships
.Where(r => !r.IsManyToMany)
.FirstOrDefault(r => r.ThisProperties.Except(parsedProperties).Count() == 0);
if (relationship == null)
continue;
bool isThisSame = relationship.ThisPropertyName == parsedRelationship.ThisPropertyName;
bool isOtherSame = relationship.OtherPropertyName == parsedRelationship.OtherPropertyName;
if (isThisSame && isOtherSame)
continue;
if (!isThisSame)
{
Debug.WriteLine("Rename Relationship Property '{0}.{1}' to '{0}.{2}'.",
relationship.ThisEntity,
relationship.ThisPropertyName,
parsedRelationship.ThisPropertyName);
relationship.ThisPropertyName = parsedRelationship.ThisPropertyName;
}
if (!isOtherSame)
{
Debug.WriteLine("Rename Relationship Property '{0}.{1}' to '{0}.{2}'.",
relationship.OtherEntity,
relationship.OtherPropertyName,
parsedRelationship.OtherPropertyName);
relationship.OtherPropertyName = parsedRelationship.OtherPropertyName;
}
// sync other relationship
var otherEntity = generatedContext.Entities.ByClass(relationship.OtherEntity);
if (otherEntity == null)
continue;
var otherRelationship = otherEntity.Relationships.ByName(relationship.RelationshipName);
if (otherRelationship == null)
continue;
otherRelationship.ThisPropertyName = relationship.OtherPropertyName;
otherRelationship.OtherPropertyName = relationship.ThisPropertyName;
}
// sync many to many
foreach (var parsedRelationship in parsedEntity.Relationships.Where(r => r.JoinTable != null))
{
var joinThisColumn = parsedRelationship.JoinThisColumn;
var joinOtherColumn = parsedRelationship.JoinOtherColumn;
var relationship = entity.Relationships
.Where(r => r.IsManyToMany)
.FirstOrDefault(r =>
r.JoinThisColumn.Except(joinThisColumn).Count() == 0 &&
r.JoinOtherColumn.Except(joinOtherColumn).Count() == 0 &&
r.JoinTable == parsedRelationship.JoinTable &&
r.JoinSchema == parsedRelationship.JoinSchema);
if (relationship == null)
continue;
bool isThisSame = relationship.ThisPropertyName == parsedRelationship.ThisPropertyName;
bool isOtherSame = relationship.OtherPropertyName == parsedRelationship.OtherPropertyName;
if (isThisSame && isOtherSame)
continue;
if (!isThisSame)
{
Debug.WriteLine("Rename Relationship Property '{0}.{1}' to '{0}.{2}'.",
relationship.ThisEntity,
relationship.ThisPropertyName,
parsedRelationship.ThisPropertyName);
relationship.ThisPropertyName = parsedRelationship.ThisPropertyName;
}
if (!isOtherSame)
{
Debug.WriteLine("Rename Relationship Property '{0}.{1}' to '{0}.{2}'.",
relationship.OtherEntity,
relationship.OtherPropertyName,
parsedRelationship.OtherPropertyName);
relationship.OtherPropertyName = parsedRelationship.OtherPropertyName;
}
// sync other relationship
var otherEntity = generatedContext.Entities.ByClass(relationship.OtherEntity);
if (otherEntity == null)
continue;
var otherRelationship = otherEntity.Relationships.ByName(relationship.RelationshipName);
if (otherRelationship == null)
continue;
otherRelationship.ThisPropertyName = relationship.OtherPropertyName;
otherRelationship.OtherPropertyName = relationship.ThisPropertyName;
}
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table
@@ -134,7 +134,7 @@ Description: Create a list of properties from a database table
url: '/<%=ModuleName%>Manager/Add?id=' + selected,
title: '编辑',
onClose:function() {
refreshModuleGrid();
refresh<%=ModuleName%>Grid();
}
});

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: Database Table Properties
Author: yubaolee
Description: 没有树状导航的datagrid
@@ -98,7 +98,7 @@ Description: 没有树状导航的datagrid
url: '/<%=ModuleName%>Manager/Add?id=' + selected,
title: '编辑',
onClose:function() {
refreshModuleGrid();
refresh<%=ModuleName%>Grid();
}
});

View File

@@ -1,4 +1,4 @@
<%--
<%--
Name: 数据访问
Author: yubaolee
Description:
@@ -20,7 +20,7 @@ namespace OpenAuth.Repository
public IEnumerable<<%=ModuleName%>> Load<%=ModuleName%>s(int pageindex, int pagesize)
{
return Context.Categories.OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
return Context.<%=ModuleName%>s.OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
}
public IEnumerable<<%=ModuleName%>> LoadInOrgs(params int[] orgId)

View File

@@ -1,11 +1,9 @@
using OpenAuth.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure;
using Infrastructure.Helper;
using Infrastructure;
using OpenAuth.App.ViewModel;
using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
using System;
using System.Linq;
namespace OpenAuth.App
{
@@ -16,18 +14,21 @@ namespace OpenAuth.App
private IRelevanceRepository _relevanceRepository;
private IRepository<ModuleElement> _moduleElementRepository;
private IResourceRepository _resourceRepository;
private IOrgRepository _orgRepository;
public LoginApp(IUserRepository repository,
IModuleRepository moduleRepository,
IRelevanceRepository relevanceRepository,
IRepository<ModuleElement> moduleElementRepository,
IResourceRepository resourceRepository)
IRepository<ModuleElement> moduleElementRepository,
IResourceRepository resourceRepository,
IOrgRepository orgRepository)
{
_repository = repository;
_moduleRepository = moduleRepository;
_relevanceRepository = relevanceRepository;
_moduleElementRepository = moduleElementRepository;
_resourceRepository = resourceRepository;
_orgRepository = orgRepository;
}
public LoginUserVM Login(string userName, string password)
@@ -52,7 +53,7 @@ namespace OpenAuth.App
_relevanceRepository.Find(
u =>
(u.FirstId == user.Id && u.Key == "UserModule") ||
(u.Key == "RoleModule" && userRoleIds.Contains(u.FirstId))).Select(u =>u.SecondId).ToList();
(u.Key == "RoleModule" && userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId).ToList();
//用户角色与自己分配到的菜单ID
var elementIds =
_relevanceRepository.Find(
@@ -60,12 +61,12 @@ namespace OpenAuth.App
(u.FirstId == user.Id && u.Key == "UserElement") ||
(u.Key == "RoleElement" && userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId).ToList();
//得出最终用户拥有的模块
loginVM.Modules = _moduleRepository.Find(u => moduleIds.Contains(u.Id)).MapToList<ModuleView>();
loginVM.Modules = _moduleRepository.Find(u => moduleIds.Contains(u.Id)).OrderBy(u => u.SortNo).MapToList<ModuleView>();
//模块菜单权限
foreach (var module in loginVM.Modules)
{
module.Elements = _moduleElementRepository.Find(u => u.ModuleId == module.Id && elementIds.Contains( u.Id)).ToList();
module.Elements = _moduleElementRepository.Find(u => u.ModuleId == module.Id && elementIds.Contains(u.Id)).OrderBy(u => u.Sort).ToList();
}
//用户角色与自己分配到的资源ID
@@ -75,6 +76,13 @@ namespace OpenAuth.App
(u.Key == "RoleResource" && userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId).ToList();
loginVM.Resources = _resourceRepository.Find(u => resourceIds.Contains(u.Id)).ToList();
//用户角色与自己分配到的机构ID
var orgids = _relevanceRepository.Find(
u =>
(u.FirstId == user.Id && u.Key == "UserAccessedOrg") ||
(u.Key == "RoleAccessdOrg" && userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId).ToList();
loginVM.AccessedOrgs = _orgRepository.Find(u => orgids.Contains(u.Id)).ToList();
return loginVM;
}
@@ -94,10 +102,12 @@ namespace OpenAuth.App
//模块包含的菜单
foreach (var module in loginUser.Modules)
{
module.Elements = _moduleElementRepository.Find(u => u.ModuleId == module.Id).ToList();
module.Elements = _moduleElementRepository.Find(u => u.ModuleId == module.Id).OrderBy(u => u.Sort).ToList();
}
loginUser.Resources = _resourceRepository.Find(null).ToList();
loginUser.Resources = _resourceRepository.Find(null).OrderBy(u => u.SortNo).ToList();
loginUser.AccessedOrgs = _orgRepository.Find(null).OrderBy(u => u.SortNo).ToList();
return loginUser;
}
}

View File

@@ -52,7 +52,7 @@ namespace OpenAuth.App
public IEnumerable<ModuleElement> LoadByModuleId(int id)
{
var modules = _repository.Find(u => u.ModuleId == id);
var modules = _repository.Find(u => u.ModuleId == id).OrderBy(u =>u.Sort);
return modules;
}

View File

@@ -49,6 +49,7 @@
<Compile Include="ModuleManagerApp.cs" />
<Compile Include="ResourceManagerApp.cs" />
<Compile Include="RoleManagerApp.cs" />
<Compile Include="StockManagerApp.cs" />
<Compile Include="UserManagerApp.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="OrgManagerApp.cs" />

View File

@@ -9,10 +9,12 @@ namespace OpenAuth.App
public class OrgManagerApp
{
private IOrgRepository _repository;
private IRelevanceRepository _relevanceRepository;
public OrgManagerApp(IOrgRepository repository)
public OrgManagerApp(IOrgRepository repository, IRelevanceRepository relevanceRepository)
{
_repository = repository;
_relevanceRepository = relevanceRepository;
}
public IList<Org> GetAll()
@@ -81,6 +83,65 @@ namespace OpenAuth.App
_repository.Delete(u => u.CascadeId.Contains(delOrg.CascadeId));
}
/// <summary>
/// 加载特定用户的角色
/// TODO:这里会加载用户及用户角色的所有角色,“为用户分配角色”功能会给人一种混乱的感觉,但可以接受
/// </summary>
/// <param name="userId">The user unique identifier.</param>
public List<Org> LoadForUser(int userId)
{
//用户角色
var userRoleIds =
_relevanceRepository.Find(u => u.FirstId == userId && u.Key == "UserRole").Select(u => u.SecondId).ToList();
//用户角色与自己分配到的角色ID
var moduleIds =
_relevanceRepository.Find(
u =>
(u.FirstId == userId && u.Key == "UserAccessedOrg") ||
(u.Key == "RoleAccessedOrg" && userRoleIds.Contains(u.FirstId))).Select(u => u.SecondId).ToList();
if (!moduleIds.Any()) return new List<Org>();
return _repository.Find(u => moduleIds.Contains(u.Id)).ToList();
}
/// <summary>
/// 为特定的用户分配角色
/// </summary>
/// <param name="userId">The user unique identifier.</param>
/// <param name="ids">角色ID</param>
public void AssignModuleForUser(int userId, int[] ids)
{
_relevanceRepository.DeleteBy("UserAccessedOrg", userId);
_relevanceRepository.AddRelevance("UserAccessedOrg", ids.ToLookup(u => userId));
}
/// <summary>
/// 加载特定角色的角色
/// </summary>
/// <param name="roleId">The role unique identifier.</param>
public List<Org> LoadForRole(int roleId)
{
var moduleIds =
_relevanceRepository.Find(u => u.FirstId == roleId && u.Key == "RoleAccessedOrg")
.Select(u => u.SecondId)
.ToList();
if (!moduleIds.Any()) return new List<Org>();
return _repository.Find(u => moduleIds.Contains(u.Id)).ToList();
}
/// <summary>
/// 为特定的角色分配角色
/// </summary>
/// <param name="roleId">The user unique identifier.</param>
/// <param name="ids">角色ID</param>
public void AssignModuleForRole(int roleId, int[] ids)
{
_relevanceRepository.DeleteBy("RoleAccessedOrg", roleId);
_relevanceRepository.AddRelevance("RoleAccessedOrg", ids.ToLookup(u => roleId));
}
#region
//修改对象的级联ID生成类似XXX.XXX.X.XX

View File

@@ -0,0 +1,107 @@

using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure;
namespace OpenAuth.App
{
public class StockManagerApp
{
private IStockRepository _repository;
private IOrgRepository _orgRepository;
public StockManagerApp(IStockRepository repository,
IOrgRepository orgRepository)
{
_repository = repository;
_orgRepository = orgRepository;
}
public int GetStockCntInOrg(int orgId)
{
if (orgId == 0)
{
return _repository.Find(null).Count();
}
else
{
return _repository.GetStockCntInOrgs(GetSubOrgIds(orgId));
}
}
public List<Stock> LoadAll()
{
return _repository.Find(null).ToList();
}
/// <summary>
/// 加载一个节点下面的一个或全部Stocks
/// </summary>
public dynamic Load(int orgId, int pageindex, int pagesize)
{
IEnumerable<Stock> Stocks;
int total = 0;
if (orgId == 0)
{
Stocks = _repository.LoadStocks(pageindex, pagesize);
total = _repository.GetCount();
}
else
{
Stocks = _repository.LoadInOrgs(pageindex, pagesize,GetSubOrgIds(orgId));
total = _repository.GetStockCntInOrgs(orgId);
}
return new
{
total = total,
list = Stocks,
pageCurrent = pageindex
};
}
/// <summary>
/// 获取当前节点的所有下级节点
/// </summary>
private int[] GetSubOrgIds(int orgId)
{
var org = _orgRepository.FindSingle(u => u.Id == orgId);
var orgs = _orgRepository.Find(u => u.CascadeId.Contains(org.CascadeId)).Select(u => u.Id).ToArray();
return orgs;
}
public Stock Find(int id)
{
var stock = _repository.FindSingle(u => u.Id == id);
if (stock == null) return new Stock();
return stock;
}
public void Delete(int id)
{
_repository.Delete(id);
}
public void AddOrUpdate(Stock model)
{
Stock stock = new Stock();
model.CopyTo(stock);
if (stock.Id == 0)
{
_repository.Add(stock);
}
else
{
_repository.Update(stock);
}
}
}
}

View File

@@ -35,6 +35,11 @@ namespace OpenAuth.App.ViewModel
/// 用户所属机构
/// </summary>
public List<Org> Orgs { get; set; }
/// <summary>
/// 用户可访问的机构
/// </summary>
public List<Org> AccessedOrgs { get; set; }
}
}

View File

@@ -1,77 +1,67 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 分类
/// <summary>
/// 分类表
/// </summary>
public partial class Category
{
/// <summary>
/// 分类ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Category
{
public Category()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.ParentId= 0;
this.Status= 0;
this.SortNo= 0;
this.RootKey= string.Empty;
this.RootName= string.Empty;
}
/// <summary>
/// 节点语义ID
/// </summary>
/// <returns></returns>
public string CascadeId { get; set; }
/// <summary>
/// 分类表ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 节点语义ID
/// </summary>
public string CascadeId { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
public int ParentId { get; set; }
/// <summary>
/// 当前状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 分类所属科目
/// </summary>
public string RootKey { get; set; }
/// <summary>
/// 分类所属科目名称
/// </summary>
public string RootName { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
/// <returns></returns>
public int ParentId { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public string RootKey { get; set; }
/// <summary>
/// 资源分类
/// </summary>
/// <returns></returns>
public string RootName { get; set; }
public Category()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.ParentId= 0;
this.Status= 0;
this.SortNo= 0;
this.RootKey= string.Empty;
this.RootName= string.Empty;
}
}
}
}

View File

@@ -1,70 +1,62 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// <summary>
/// 数据字典详情
/// </summary>
public partial class DicDetail
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class DicDetail
{
public DicDetail()
{
this.Id= 0;
this.Value= string.Empty;
this.Text= string.Empty;
this.DicId= 0;
this.SortNo= 0;
this.Status= 0;
this.Description= string.Empty;
}
/// <summary>
/// 名称
/// </summary>
/// <returns></returns>
public string Value { get; set; }
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 值
/// </summary>
public string Value { get; set; }
/// <summary>
/// 文本描述
/// </summary>
public string Text { get; set; }
/// <summary>
/// 所属字典ID
/// </summary>
public int DicId { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Text { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public int DicId { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 描述
/// </summary>
/// <returns></returns>
public string Description { get; set; }
public DicDetail()
{
this.Id= 0;
this.Value= string.Empty;
this.Text= string.Empty;
this.DicId= 0;
this.SortNo= 0;
this.Status= 0;
this.Description= string.Empty;
}
}
}
}

View File

@@ -1,63 +1,57 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// <summary>
/// 数据字典
/// </summary>
public partial class DicIndex
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class DicIndex
{
public DicIndex()
{
this.Id= 0;
this.Name= string.Empty;
this.Key= string.Empty;
this.SortNo= 0;
this.CategoryId= 0;
this.Description= string.Empty;
}
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 数据字典ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public string Key { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 所属分类
/// </summary>
public int CategoryId { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Key { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int CategoryId { get; set; }
/// <summary>
/// 描述
/// </summary>
/// <returns></returns>
public string Description { get; set; }
public DicIndex()
{
this.Id= 0;
this.Name= string.Empty;
this.Key= string.Empty;
this.SortNo= 0;
this.CategoryId= 0;
this.Description= string.Empty;
}
}
}
}

View File

@@ -0,0 +1,17 @@
using System.Collections.Generic;
using System.Linq;
namespace OpenAuth.Domain.Interface
{
public interface IStockRepository :IRepository<Stock>
{
IEnumerable<Stock> LoadStocks(int pageindex, int pagesize);
IEnumerable<Stock> LoadInOrgs(params int[] orgId);
int GetStockCntInOrgs(params int[] orgIds);
IEnumerable<Stock> LoadInOrgs(int pageindex, int pagesize, params int[] orgIds);
void Delete(int id);
}
}

View File

@@ -1,112 +1,90 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 模块
/// <summary>
/// 功能模块
/// </summary>
public partial class Module
{
/// <summary>
/// 模块ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Module
{
public Module()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.Url= string.Empty;
this.HotKey= string.Empty;
this.ParentId= 0;
this.IconName= string.Empty;
this.Status= 0;
this.ParentName= string.Empty;
this.Vector= string.Empty;
this.SortNo= 0;
}
/// <summary>
/// 节点语义ID
/// </summary>
/// <returns></returns>
public string CascadeId { get; set; }
/// <summary>
/// 功能模块流水号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 节点语义ID
/// </summary>
public string CascadeId { get; set; }
/// <summary>
/// 功能模块名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 主页面URL
/// </summary>
public string Url { get; set; }
/// <summary>
/// 热键
/// </summary>
public string HotKey { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
public int ParentId { get; set; }
/// <summary>
/// 是否叶子节点
/// </summary>
public bool IsLeaf { get; set; }
/// <summary>
/// 是否自动展开
/// </summary>
public bool IsAutoExpand { get; set; }
/// <summary>
/// 节点图标文件名称
/// </summary>
public string IconName { get; set; }
/// <summary>
/// 当前状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 父节点名称
/// </summary>
public string ParentName { get; set; }
/// <summary>
/// 矢量图标
/// </summary>
public string Vector { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 主页面URL
/// </summary>
/// <returns></returns>
public string Url { get; set; }
/// <summary>
/// 热键
/// </summary>
/// <returns></returns>
public string HotKey { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
/// <returns></returns>
public int ParentId { get; set; }
/// <summary>
/// 是否叶子节点
/// </summary>
/// <returns></returns>
public bool IsLeaf { get; set; }
/// <summary>
/// 是否自动展开
/// </summary>
/// <returns></returns>
public bool IsAutoExpand { get; set; }
/// <summary>
/// 节点图标文件名称
/// </summary>
/// <returns></returns>
public string IconName { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 父节点名称
/// </summary>
/// <returns></returns>
public string ParentName { get; set; }
/// <summary>
/// 矢量图标
/// </summary>
/// <returns></returns>
public string Vector { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
public Module()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.Url= string.Empty;
this.HotKey= string.Empty;
this.ParentId= 0;
this.IsLeaf= false;
this.IsAutoExpand= false;
this.IconName= string.Empty;
this.Status= 0;
this.ParentName= string.Empty;
this.Vector= string.Empty;
this.SortNo= 0;
}
}
}
}

View File

@@ -1,98 +1,82 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 模块元素
/// <summary>
/// 模块元素表(需要权限控制的按钮)
/// </summary>
public partial class ModuleElement
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class ModuleElement
{
public ModuleElement()
{
this.Id= 0;
this.DomId= string.Empty;
this.Name= string.Empty;
this.Type= string.Empty;
this.ModuleId= 0;
this.Attr= string.Empty;
this.Script= string.Empty;
this.Icon= string.Empty;
this.Class= string.Empty;
this.Remark= string.Empty;
this.Sort= 0;
}
/// <summary>
/// DOM ID
/// </summary>
/// <returns></returns>
public string DomId { get; set; }
/// <summary>
/// 流水号
/// </summary>
public int Id { get; set; }
/// <summary>
/// DOM ID
/// </summary>
public string DomId { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 功能模块Id
/// </summary>
public int ModuleId { get; set; }
/// <summary>
/// 元素附加属性
/// </summary>
public string Attr { get; set; }
/// <summary>
/// 元素调用脚本
/// </summary>
public string Script { get; set; }
/// <summary>
/// 元素图标
/// </summary>
public string Icon { get; set; }
/// <summary>
/// 元素样式
/// </summary>
public string Class { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 排序字段
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 组织类型
/// </summary>
/// <returns></returns>
public string Type { get; set; }
/// <summary>
/// 功能模块Id
/// </summary>
/// <returns></returns>
public int ModuleId { get; set; }
/// <summary>
/// 元素附加属性
/// </summary>
/// <returns></returns>
public string Attr { get; set; }
/// <summary>
/// 元素调用脚本
/// </summary>
/// <returns></returns>
public string Script { get; set; }
/// <summary>
/// 元素图标
/// </summary>
/// <returns></returns>
public string Icon { get; set; }
/// <summary>
/// 元素样式
/// </summary>
/// <returns></returns>
public string Class { get; set; }
/// <summary>
/// 备注
/// </summary>
/// <returns></returns>
public string Remark { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public int Sort { get; set; }
public ModuleElement()
{
this.Id= 0;
this.DomId= string.Empty;
this.Name= string.Empty;
this.Type= string.Empty;
this.ModuleId= 0;
this.Attr= string.Empty;
this.Script= string.Empty;
this.Icon= string.Empty;
this.Class= string.Empty;
this.Remark= string.Empty;
this.Sort= 0;
}
}
}
}

View File

@@ -53,6 +53,7 @@
<Compile Include="Interface\IResourceRepository.cs" />
<Compile Include="Interface\IRoleRepository.cs" />
<Compile Include="Interface\IRelevanceRepository.cs" />
<Compile Include="Interface\IStockRepository.cs" />
<Compile Include="Interface\IUserRepository.cs" />
<Compile Include="Module.cs" />
<Compile Include="ModuleElement.cs" />
@@ -62,6 +63,7 @@
<Compile Include="Relevance.cs" />
<Compile Include="Resource.cs" />
<Compile Include="Role.cs" />
<Compile Include="Stock.cs" />
<Compile Include="User.cs" />
<Compile Include="UserCfg.cs" />
<Compile Include="UserExt.cs" />

View File

@@ -1,133 +1,105 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 组织
/// <summary>
/// 组织
/// </summary>
public partial class Org
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Org
{
public Org()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.HotKey= string.Empty;
this.ParentId= 0;
this.ParentName= string.Empty;
this.IconName= string.Empty;
this.Status= 0;
this.Type= 0;
this.BizCode= string.Empty;
this.CustomCode= string.Empty;
this.CreateTime= DateTime.Now;
this.CreateId= 0;
this.SortNo= 0;
}
/// <summary>
/// 节点语义ID
/// </summary>
/// <returns></returns>
public string CascadeId { get; set; }
/// <summary>
/// 流水号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 节点语义ID
/// </summary>
public string CascadeId { get; set; }
/// <summary>
/// 组织名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 热键
/// </summary>
public string HotKey { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
public int ParentId { get; set; }
/// <summary>
/// 父节点名称
/// </summary>
public string ParentName { get; set; }
/// <summary>
/// 是否叶子节点
/// </summary>
public bool IsLeaf { get; set; }
/// <summary>
/// 是否自动展开
/// </summary>
public bool IsAutoExpand { get; set; }
/// <summary>
/// 节点图标文件名称
/// </summary>
public string IconName { get; set; }
/// <summary>
/// 当前状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 组织类型
/// </summary>
public int Type { get; set; }
/// <summary>
/// 业务对照码
/// </summary>
public string BizCode { get; set; }
/// <summary>
/// 自定义扩展码
/// </summary>
public string CustomCode { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
public int CreateId { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 热键
/// </summary>
/// <returns></returns>
public string HotKey { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
/// <returns></returns>
public int ParentId { get; set; }
/// <summary>
/// 父节点名称
/// </summary>
/// <returns></returns>
public string ParentName { get; set; }
/// <summary>
/// 是否叶子节点
/// </summary>
/// <returns></returns>
public bool IsLeaf { get; set; }
/// <summary>
/// 是否自动展开
/// </summary>
/// <returns></returns>
public bool IsAutoExpand { get; set; }
/// <summary>
/// 节点图标文件名称
/// </summary>
/// <returns></returns>
public string IconName { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 组织类型
/// </summary>
/// <returns></returns>
public int Type { get; set; }
/// <summary>
/// 业务对照码
/// </summary>
/// <returns></returns>
public string BizCode { get; set; }
/// <summary>
/// 自定义扩展码
/// </summary>
/// <returns></returns>
public string CustomCode { get; set; }
/// <summary>
/// 创建时间
/// </summary>
/// <returns></returns>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
/// <returns></returns>
public int CreateId { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
public Org()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Name= string.Empty;
this.HotKey= string.Empty;
this.ParentId= 0;
this.ParentName= string.Empty;
this.IsLeaf= false;
this.IsAutoExpand= false;
this.IconName= string.Empty;
this.Status= 0;
this.Type= 0;
this.BizCode= string.Empty;
this.CustomCode= string.Empty;
this.CreateTime= DateTime.Now;
this.CreateId= 0;
this.SortNo= 0;
}
}
}
}

View File

@@ -1,70 +1,62 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 键值
/// <summary>
/// 键值参数
/// </summary>
public partial class Param
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Param
{
public Param()
{
this.Id= 0;
this.Value= string.Empty;
this.Key= string.Empty;
this.CategoryId= 0;
this.SortNo= 0;
this.Status= 0;
this.Description= string.Empty;
}
/// <summary>
/// 名称
/// </summary>
/// <returns></returns>
public string Value { get; set; }
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 值
/// </summary>
public string Value { get; set; }
/// <summary>
///
/// </summary>
public string Key { get; set; }
/// <summary>
/// 所属分类
/// </summary>
public int CategoryId { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Key { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int CategoryId { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 描述
/// </summary>
/// <returns></returns>
public string Description { get; set; }
public Param()
{
this.Id= 0;
this.Value= string.Empty;
this.Key= string.Empty;
this.CategoryId= 0;
this.SortNo= 0;
this.Status= 0;
this.Description= string.Empty;
}
}
}
}

View File

@@ -1,77 +1,67 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 多对多映射
/// <summary>
/// 多对多关系集中映射
/// </summary>
public partial class Relevance
{
/// <summary>
/// ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Relevance
{
public Relevance()
{
this.Id= 0;
this.FirstId= 0;
this.SecondId= 0;
this.Description= string.Empty;
this.Key= string.Empty;
this.Status= 0;
this.OperateTime= DateTime.Now;
this.OperatorId= 0;
}
/// <summary>
/// 第一个表主键ID
/// </summary>
/// <returns></returns>
public int FirstId { get; set; }
/// <summary>
/// 流水号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 第一个表主键ID
/// </summary>
public int FirstId { get; set; }
/// <summary>
/// 第二个表主键ID
/// </summary>
public int SecondId { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
public string Key { get; set; }
/// <summary>
/// 状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 授权时间
/// </summary>
public System.DateTime OperateTime { get; set; }
/// <summary>
/// 授权人
/// </summary>
public int OperatorId { get; set; }
/// <summary>
/// 第二个表主键ID
/// </summary>
/// <returns></returns>
public int SecondId { get; set; }
/// <summary>
/// 描述
/// </summary>
/// <returns></returns>
public string Description { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Key { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 授权时间
/// </summary>
/// <returns></returns>
public System.DateTime OperateTime { get; set; }
/// <summary>
/// 授权人
/// </summary>
/// <returns></returns>
public int OperatorId { get; set; }
public Relevance()
{
this.Id= 0;
this.FirstId= 0;
this.SecondId= 0;
this.Description= string.Empty;
this.Key= string.Empty;
this.Status= 0;
this.OperateTime= DateTime.Now;
this.OperatorId= 0;
}
}
}
}

View File

@@ -1,84 +1,72 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 资源表ID
/// <summary>
/// 资源表
/// </summary>
public partial class Resource
{
/// <summary>
/// 资源表ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Resource
{
public Resource()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Key= string.Empty;
this.Name= string.Empty;
this.ParentId= 0;
this.Status= 0;
this.SortNo= 0;
this.CategoryId= 0;
this.Description= string.Empty;
}
/// <summary>
/// 节点语义ID
/// </summary>
/// <returns></returns>
public string CascadeId { get; set; }
/// <summary>
/// 资源表ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 节点语义ID
/// </summary>
public string CascadeId { get; set; }
/// <summary>
///
/// </summary>
public string Key { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
public int ParentId { get; set; }
/// <summary>
/// 当前状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 排序号
/// </summary>
public int SortNo { get; set; }
/// <summary>
/// 资源分类
/// </summary>
public int CategoryId { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Key { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 父节点流水号
/// </summary>
/// <returns></returns>
public int ParentId { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 排序号
/// </summary>
/// <returns></returns>
public int SortNo { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int CategoryId { get; set; }
/// <summary>
/// 描述
/// </summary>
/// <returns></returns>
public string Description { get; set; }
public Resource()
{
this.Id= 0;
this.CascadeId= string.Empty;
this.Key= string.Empty;
this.Name= string.Empty;
this.ParentId= 0;
this.Status= 0;
this.SortNo= 0;
this.CategoryId= 0;
this.Description= string.Empty;
}
}
}
}

View File

@@ -1,84 +1,72 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 角色
/// <summary>
/// 角色
/// </summary>
public partial class Role
{
/// <summary>
/// 资源表ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class Role
{
public Role()
{
this.Id= 0;
this.Name= string.Empty;
this.Status= 0;
this.Type= 0;
this.CreateTime= DateTime.Now;
this.CreateId= string.Empty;
this.OrgId= 0;
this.OrgCascadeId= string.Empty;
this.OrgName= string.Empty;
}
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
/// 流水号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 角色名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 当前状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 角色类型
/// </summary>
public int Type { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
public string CreateId { get; set; }
/// <summary>
/// 所属部门流水号
/// </summary>
public int OrgId { get; set; }
/// <summary>
/// 所属部门节点语义ID
/// </summary>
public string OrgCascadeId { get; set; }
/// <summary>
/// 所属部门名称
/// </summary>
public string OrgName { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 组织类型
/// </summary>
/// <returns></returns>
public int Type { get; set; }
/// <summary>
/// 创建时间
/// </summary>
/// <returns></returns>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
/// <returns></returns>
public string CreateId { get; set; }
/// <summary>
/// 所属部门流水号
/// </summary>
/// <returns></returns>
public int OrgId { get; set; }
/// <summary>
/// 所属部门节点语义ID
/// </summary>
/// <returns></returns>
public string OrgCascadeId { get; set; }
/// <summary>
/// 所属部门名称
/// </summary>
/// <returns></returns>
public string OrgName { get; set; }
public Role()
{
this.Id= 0;
this.Name= string.Empty;
this.Status= 0;
this.Type= 0;
this.CreateTime= DateTime.Now;
this.CreateId= string.Empty;
this.OrgId= 0;
this.OrgCascadeId= string.Empty;
this.OrgName= string.Empty;
}
}
}
}

67
OpenAuth.Domain/Stock.cs Normal file
View File

@@ -0,0 +1,67 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 出入库信息表
/// </summary>
public partial class Stock
{
public Stock()
{
this.Id= 0;
this.Name= string.Empty;
this.Number= 0;
this.Price= 0;
this.Status= 0;
this.User= string.Empty;
this.Time= DateTime.Now;
this.OrgId= 0;
}
/// <summary>
/// 数据ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 产品数量
/// </summary>
public int Number { get; set; }
/// <summary>
/// 产品单价
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// 出库/入库
/// </summary>
public int Status { get; set; }
/// <summary>
///
/// </summary>
public string User { get; set; }
/// <summary>
/// 操作时间
/// </summary>
public System.DateTime Time { get; set; }
/// <summary>
/// 组织ID
/// </summary>
public int OrgId { get; set; }
}
}

View File

@@ -1,91 +1,77 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 用户
/// <summary>
///
/// </summary>
public partial class User
{
/// <summary>
/// 资源表ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class User
{
public User()
{
this.Id= 0;
this.Account= string.Empty;
this.Password= string.Empty;
this.Name= string.Empty;
this.Sex= 0;
this.Status= 0;
this.Type= 0;
this.BizCode= string.Empty;
this.CreateTime= DateTime.Now;
this.CreateId= 0;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Account { get; set; }
/// <summary>
///
/// </summary>
public int Id { get; set; }
/// <summary>
///
/// </summary>
public string Account { get; set; }
/// <summary>
///
/// </summary>
public string Password { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
///
/// </summary>
public int Sex { get; set; }
/// <summary>
///
/// </summary>
public int Status { get; set; }
/// <summary>
///
/// </summary>
public int Type { get; set; }
/// <summary>
///
/// </summary>
public string BizCode { get; set; }
/// <summary>
///
/// </summary>
public System.DateTime CreateTime { get; set; }
/// <summary>
///
/// </summary>
public int CreateId { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public string Password { get; set; }
/// <summary>
/// 组织名称
/// </summary>
/// <returns></returns>
public string Name { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public int Sex { get; set; }
/// <summary>
/// 资源分类标识
/// </summary>
/// <returns></returns>
public int Status { get; set; }
/// <summary>
/// 组织类型
/// </summary>
/// <returns></returns>
public int Type { get; set; }
/// <summary>
/// 业务对照码
/// </summary>
/// <returns></returns>
public string BizCode { get; set; }
/// <summary>
/// 创建时间
/// </summary>
/// <returns></returns>
public System.DateTime CreateTime { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
/// <returns></returns>
public int CreateId { get; set; }
public User()
{
this.Id= 0;
this.Account= string.Empty;
this.Password= string.Empty;
this.Name= string.Empty;
this.Sex= 0;
this.Status= 0;
this.Type= 0;
this.BizCode= string.Empty;
this.CreateTime= DateTime.Now;
this.CreateId= 0;
}
}
}
}

View File

@@ -1,63 +1,57 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 用户配置
/// <summary>
/// 用户配置
/// </summary>
public partial class UserCfg
{
/// <summary>
/// 资源表ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class UserCfg
{
public UserCfg()
{
this.Id= 0;
this.Theme= string.Empty;
this.Skin= string.Empty;
this.NavBarStyle= string.Empty;
this.TabFocusColor= string.Empty;
this.NavTabIndex= 0;
}
/// <summary>
/// 用户界面主题
/// </summary>
/// <returns></returns>
public string Theme { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 用户界面主题
/// </summary>
public string Theme { get; set; }
/// <summary>
/// 用户界面皮肤
/// </summary>
public string Skin { get; set; }
/// <summary>
/// 导航条按钮风格
/// </summary>
public string NavBarStyle { get; set; }
/// <summary>
/// Tab高亮颜色
/// </summary>
public string TabFocusColor { get; set; }
/// <summary>
/// 导航缺省活动页
/// </summary>
public int NavTabIndex { get; set; }
/// <summary>
/// 用户界面皮肤
/// </summary>
/// <returns></returns>
public string Skin { get; set; }
/// <summary>
/// 导航条按钮风格
/// </summary>
/// <returns></returns>
public string NavBarStyle { get; set; }
/// <summary>
/// Tab高亮颜色
/// </summary>
/// <returns></returns>
public string TabFocusColor { get; set; }
/// <summary>
/// 导航缺省活动页
/// </summary>
/// <returns></returns>
public int NavTabIndex { get; set; }
public UserCfg()
{
this.Id= 0;
this.Theme= string.Empty;
this.Skin= string.Empty;
this.NavBarStyle= string.Empty;
this.TabFocusColor= string.Empty;
this.NavTabIndex= 0;
}
}
}
}

View File

@@ -1,126 +1,102 @@
using System;
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// Author:Yubao Li
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace OpenAuth.Domain
{
/// <summary>
/// 用户扩展信息
/// <summary>
/// 用户扩展信息
/// </summary>
public partial class UserExt
{
/// <summary>
/// 资源表ID
/// </summary>
/// <returns></returns>
public int Id { get; set; }
public partial class UserExt
{
public UserExt()
{
this.Id= 0;
this.Email= string.Empty;
this.Phone= string.Empty;
this.Mobile= string.Empty;
this.Address= string.Empty;
this.Zip= string.Empty;
this.Birthday= string.Empty;
this.IdCard= string.Empty;
this.Qq= string.Empty;
this.DynamicField= string.Empty;
this.ByteArrayId= 0;
this.Remark= string.Empty;
this.Field1= string.Empty;
this.Field2= string.Empty;
this.Field3= string.Empty;
}
/// <summary>
/// 电子邮件
/// </summary>
/// <returns></returns>
public string Email { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 电子邮件
/// </summary>
public string Email { get; set; }
/// <summary>
/// 固定电话
/// </summary>
public string Phone { get; set; }
/// <summary>
/// 移动电话
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// 联系地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 邮编
/// </summary>
public string Zip { get; set; }
/// <summary>
/// 生日
/// </summary>
public string Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
public string IdCard { get; set; }
/// <summary>
/// QQ
/// </summary>
public string Qq { get; set; }
/// <summary>
/// 动态扩展字段
/// </summary>
public string DynamicField { get; set; }
/// <summary>
/// 用户头像流文件ID
/// </summary>
public int ByteArrayId { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 静态扩展字段1
/// </summary>
public string Field1 { get; set; }
/// <summary>
/// 静态扩展字段2
/// </summary>
public string Field2 { get; set; }
/// <summary>
/// 静态扩展字段3
/// </summary>
public string Field3 { get; set; }
/// <summary>
/// 固定电话
/// </summary>
/// <returns></returns>
public string Phone_ { get; set; }
/// <summary>
/// 移动电话
/// </summary>
/// <returns></returns>
public string Mobile { get; set; }
/// <summary>
/// 联系地址
/// </summary>
/// <returns></returns>
public string Address { get; set; }
/// <summary>
/// 邮编
/// </summary>
/// <returns></returns>
public string Zip { get; set; }
/// <summary>
/// 生日
/// </summary>
/// <returns></returns>
public string Birthday { get; set; }
/// <summary>
/// 身份证号
/// </summary>
/// <returns></returns>
public string IdCard { get; set; }
/// <summary>
/// QQ
/// </summary>
/// <returns></returns>
public string QQ { get; set; }
/// <summary>
/// 动态扩展字段
/// </summary>
/// <returns></returns>
public string DynamicField { get; set; }
/// <summary>
/// 用户头像流文件ID
/// </summary>
/// <returns></returns>
public int ByteArrayId { get; set; }
/// <summary>
/// 备注
/// </summary>
/// <returns></returns>
public string Remark { get; set; }
/// <summary>
/// 静态扩展字段1
/// </summary>
/// <returns></returns>
public string Field1 { get; set; }
/// <summary>
/// 静态扩展字段2
/// </summary>
/// <returns></returns>
public string Field2 { get; set; }
/// <summary>
/// 静态扩展字段3
/// </summary>
/// <returns></returns>
public string Field3 { get; set; }
public UserExt()
{
this.Id= 0;
this.Email= string.Empty;
this.Phone_= string.Empty;
this.Mobile= string.Empty;
this.Address= string.Empty;
this.Zip= string.Empty;
this.Birthday= string.Empty;
this.IdCard= string.Empty;
this.QQ= string.Empty;
this.DynamicField= string.Empty;
this.ByteArrayId= 0;
this.Remark= string.Empty;
this.Field1= string.Empty;
this.Field2= string.Empty;
this.Field3= string.Empty;
}
}
}
}

View File

@@ -42,6 +42,7 @@ namespace OpenAuth.Mvc
builder.RegisterType<ModuleElementManagerApp>();
builder.RegisterType<CategoryManagerApp>();
builder.RegisterType<ResourceManagerApp>();
builder.RegisterType<StockManagerApp>();
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
@@ -65,7 +66,7 @@ namespace OpenAuth.Mvc
}
/// <summary>
/// <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ
/// 从容器中获取对象
/// </summary>
/// <typeparam name="T"></typeparam>
public static T GetFromFac<T>()

View File

@@ -3,7 +3,10 @@ using OpenAuth.App;
using OpenAuth.Domain;
using OpenAuth.Mvc.Models;
using System;
using System.Linq;
using System.Web.Mvc;
using Infrastructure.Helper;
using OpenAuth.App.ViewModel;
namespace OpenAuth.Mvc.Controllers
{
@@ -23,6 +26,20 @@ namespace OpenAuth.Mvc.Controllers
return View();
}
//用于选择模块时使用
public ActionResult LookUpMultiForUser(int userId)
{
ViewBag.UserId = userId;
return View();
}
//为角色分配模块
public ActionResult LookupMultiForRole(int roleId)
{
ViewBag.RoleId = roleId;
return View();
}
/// <summary>
/// 选择上级机构页面
/// </summary>
@@ -37,6 +54,86 @@ namespace OpenAuth.Mvc.Controllers
return View();
}
public string LoadForTree()
{
var orgs = SessionHelper.GetSessionUser<LoginUserVM>().AccessedOrgs;
return JsonHelper.Instance.Serialize(orgs);
}
public string LoadOrgWithRoot()
{
var orgs = SessionHelper.GetSessionUser<LoginUserVM>().AccessedOrgs;
//添加根节点
orgs.Add(new Org
{
Id = 0,
ParentId = -1,
Name = "根节点",
CascadeId = "0"
});
return JsonHelper.Instance.Serialize(orgs);
}
public string LoadForUser(int userId)
{
var orgs = _orgApp.LoadForUser(userId);
//添加根节点
orgs.Add(new Org
{
Id = 0,
ParentId = -1,
Name = "用户及角色可访问的部门",
CascadeId = "0"
});
return JsonHelper.Instance.Serialize(orgs);
}
public string LoadForRole(int roleId)
{
var orgs = _orgApp.LoadForRole(roleId);
//添加根节点
orgs.Add(new Org
{
Id = 0,
ParentId = -1,
Name = "已为角色分配的可访问部门",
CascadeId = "0"
});
return JsonHelper.Instance.Serialize(orgs);
}
public string AssignOrgForRole(int roleId, string moduleIds)
{
try
{
var ids = moduleIds.Split(',').Select(id => int.Parse(id)).ToArray();
_orgApp.AssignModuleForRole(roleId, ids);
}
catch (Exception e)
{
BjuiResponse.message = e.Message;
BjuiResponse.statusCode = "300";
}
return JsonHelper.Instance.Serialize(BjuiResponse);
}
public string AssignOrgForUser(int userId, string moduleIds)
{
try
{
var ids = moduleIds.Split(',').Select(id => int.Parse(id)).ToArray();
_orgApp.AssignModuleForUser(userId, ids);
}
catch (Exception e)
{
BjuiResponse.message = e.Message;
BjuiResponse.statusCode = "300";
}
return JsonHelper.Instance.Serialize(BjuiResponse);
}
//添加组织提交
[HttpPost]
public string AddOrg(Org org)

View File

@@ -0,0 +1,82 @@
using Infrastructure;
using OpenAuth.App;
using OpenAuth.Domain;
using System;
using System.Web.Mvc;
namespace OpenAuth.Mvc.Controllers
{
public class StockManagerController : BaseController
{
private StockManagerApp _app;
public StockManagerController()
{
_app = AutofacExt.GetFromFac<StockManagerApp>();
}
//
// GET: /UserManager/
public ActionResult Index()
{
return View();
}
public ActionResult Add(int id = 0)
{
return View(_app.Find(id));
}
//添加或修改Stock
[HttpPost]
public string Add(Stock model)
{
try
{
_app.AddOrUpdate(model);
}
catch (Exception ex)
{
BjuiResponse.statusCode = "300";
BjuiResponse.message = ex.Message;
}
return JsonHelper.Instance.Serialize(BjuiResponse);
}
/// <summary>
/// 加载节点下面的所有Stocks
/// </summary>
public string Load(int parentidId, int pageCurrent = 1, int pageSize = 30)
{
return JsonHelper.Instance.Serialize(_app.Load(parentidId, pageCurrent, pageSize));
}
public string LoadForTree()
{
var models = _app.LoadAll();
//添加根节点
models.Add(new Stock
{
Id = 0,
OrgId = -1,
Name = "根结点",
});
return JsonHelper.Instance.Serialize(models);
}
public string Delete(int Id)
{
try
{
_app.Delete(Id);
}
catch (Exception e)
{
BjuiResponse.statusCode = "300";
BjuiResponse.message = e.Message;
}
return JsonHelper.Instance.Serialize(BjuiResponse);
}
}
}

View File

@@ -132,6 +132,7 @@
<Compile Include="Controllers\OrgManagerController.cs" />
<Compile Include="Controllers\ResourceManagerController.cs" />
<Compile Include="Controllers\RoleManagerController.cs" />
<Compile Include="Controllers\StockManagerController.cs" />
<Compile Include="Controllers\UserManagerController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
@@ -574,6 +575,10 @@
<Content Include="Views\RoleManager\LookupMulti.cshtml" />
<Content Include="Views\ResourceManager\LookupMultiForUser.cshtml" />
<Content Include="Views\ResourceManager\LookupMultiForRole.cshtml" />
<Content Include="Views\StockManager\Index.cshtml" />
<Content Include="Views\StockManager\Add.cshtml" />
<Content Include="Views\OrgManager\LookupMultiForRole.cshtml" />
<Content Include="Views\OrgManager\LookupMultiForUser.cshtml" />
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />

View File

@@ -0,0 +1,123 @@
@*
选择多个模块ID以ids的形式返回
*@
@{
ViewBag.Title = "title";
Layout = null;
}
<div class="bjui-pageContent">
<input style="display: none" id="roleId" value="@ViewBag.RoleId"/>
<div style="float: left; width: 220px; height: 240px; overflow: auto;" class="table table-bordered">
<ul id="lookupTree" class="ztree"></ul>
</div>
<!--已经选中的列表-->
<div style="margin-left: 225px">
<ul id="selected" class="ztree"></ul>
</div>
</div>
<div class="bjui-pageFooter">
<ul>
<li><button type="button" class="btn-close" data-icon="close">关闭</button></li>
<li><button type="button" onclick="save()" class="btn btn-blue" data-icon="check">保存</button></li>
</ul>
</div>
<script type="text/javascript">
var moduleIds;
$(document).ready(function () {
Init();
InitSelected();
});
function Init() {
var setting = {
view: {
selectedMulti: false
},
check: {
enable: true,
chkStyle: "checkbox"
},
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: zTreeOnClick,
onCheck: zTreeCheck
}
};
$.getJSON('OrgManager/LoadForTree', function (json) {
var zTreeObj = $.fn.zTree.init($('#lookupTree'), setting, json);
zTreeObj.expandAll(true);
});
}
function InitSelected() {
var setting = {
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: zTreeOnClick,
onCheck: zTreeCheck
}
};
$.post('OrgManager/LoadForRole', { roleId: $('#roleId').val() },
function (json) {
var zTreeObj = $.fn.zTree.init($('#selected'), setting, eval(json));
zTreeObj.expandAll(true);
});
}
function save() {
$.post('OrgManager/AssignOrgForRole', { roleId: $('#roleId').val(), moduleIds: moduleIds },
function (json) {
var rel = $.parseJSON(json);
if (rel.statusCode == "200") {
$(this).alertmsg('ok', rel.message);
} else {
$(this).alertmsg('error', rel.message);
}
});
}
function zTreeCheck(e, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId),
nodes = zTree.getCheckedNodes(true);
var ids = '';
for (var i = 0; i < nodes.length; i++) {
ids += ',' + nodes[i].Id;
}
if (ids.length > 0) { //去掉第一个逗号
ids = ids.substr(1);
}
moduleIds = ids;
}
function zTreeOnClick(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
zTree.checkNode(treeNode, !treeNode.checked, true, true);
event.preventDefault();
}
//@@ sourceURL=lookupMultiForRole.js
</script>

View File

@@ -0,0 +1,123 @@
@*
选择多个模块ID以ids的形式返回
*@
@{
ViewBag.Title = "title";
Layout = null;
}
<div class="bjui-pageContent">
<input style="display: none" id="userId" value="@ViewBag.UserId"/>
<div style="float: left; width: 220px; height: 240px; overflow: auto;" class="table table-bordered">
<ul id="lookupTree" class="ztree"></ul>
</div>
<!--已经选中的列表-->
<div style="margin-left: 225px">
<ul id="selected" class="ztree"></ul>
</div>
</div>
<div class="bjui-pageFooter">
<ul>
<li><button type="button" class="btn-close" data-icon="close">关闭</button></li>
<li><button type="button" onclick="save()" class="btn btn-blue" data-icon="check">保存</button></li>
</ul>
</div>
<script type="text/javascript">
var moduleIds;
$(document).ready(function () {
Init();
InitSelected();
});
function Init() {
var setting = {
view: {
selectedMulti: false
},
check: {
enable: true,
chkStyle: "checkbox"
},
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: zTreeOnClick,
onCheck: zTreeCheck
}
};
$.getJSON('OrgManager/LoadForTree', function (json) {
var zTreeObj = $.fn.zTree.init($('#lookupTree'), setting, json);
zTreeObj.expandAll(true);
});
}
function InitSelected() {
var setting = {
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: zTreeOnClick,
onCheck: zTreeCheck
}
};
$.post('OrgManager/LoadForUser', { userId: $('#userId').val() },
function (json) {
var zTreeObj = $.fn.zTree.init($('#selected'), setting, eval(json));
zTreeObj.expandAll(true);
});
}
function save() {
$.post('OrgManager/AssignOrgForUser', { userId: $('#userId').val(), moduleIds: moduleIds },
function (json) {
var rel = $.parseJSON(json);
if (rel.statusCode == "200") {
$(this).alertmsg('ok', rel.message);
} else {
$(this).alertmsg('error', rel.message);
}
});
}
function zTreeCheck(e, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId),
nodes = zTree.getCheckedNodes(true);
var ids = '';
for (var i = 0; i < nodes.length; i++) {
ids += ',' + nodes[i].Id;
}
if (ids.length > 0) { //去掉第一个逗号
ids = ids.substr(1);
}
moduleIds = ids;
}
function zTreeOnClick(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
zTree.checkNode(treeNode, !treeNode.checked, true, true);
event.preventDefault();
}
//@@ sourceURL=lookupMulti.js
</script>

View File

@@ -52,7 +52,7 @@
},
{
name: 'Name',
label: '角色名称',
label: '资源名称',
width: 100
},

View File

@@ -52,7 +52,7 @@
},
{
name: 'Name',
label: '角色名称',
label: '资源名称',
width: 100
},

View File

@@ -169,6 +169,21 @@
});
}
//为角色分配可见机构
function assignRoleOrg(obj) {
var selected = getSelected('#@_gridId', 2);
if (selected == null) return;
$(obj).dialog({
id: 'accessRoleOrg',
url: '/OrgManager/LookupMultiForRole',
title: '为角色分配可见机构',
data: {
roleid: selected
}
});
}
//为角色分配资源
function openRoleReourceAccess(obj) {
var selected = getSelected('#@_gridId', 2);

View File

@@ -0,0 +1,137 @@
@model OpenAuth.Domain.Stock
@{
ViewBag.Title = "Stock编辑界面";
Layout = null;
}
<div class="bjui-pageContent">
<form action="/StockManager/Add" class="pageForm" data-toggle="validate">
<table class="table table-condensed table-hover">
<tbody>
<tr>
<td>
@Html.HiddenFor(m =>m.Id)
</td>
</tr>
<tr>
<td>
<label for="Name" class="control-label x120">产品名称:</label>
<input type="text" name="Name" id="Name" value="@Model.Name"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
<label for="Number" class="control-label x120">产品数量:</label>
<input type="text" name="Number" id="Number" value="@Model.Number"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
<label for="Price" class="control-label x120">产品单价:</label>
<input type="text" name="Price" id="Price" value="@Model.Price"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
<label for="Status" class="control-label x120">出库/入库:</label>
<input type="text" name="Status" id="Status" value="@Model.Status"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
<label for="User" class="control-label x120"></label>
<input type="text" name="User" id="User" value="@Model.User"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
<label for="Time" class="control-label x120">操作时间:</label>
<input type="text" name="Time" id="Time" value="@Model.Time"
data-rule="required" size="20">
</td>
</tr>
<tr>
<td>
@Html.HiddenFor(m =>m.OrgId)
@if (Model.Id == 0) //添加
{
//这个只用于显示使用并不会进行提交处理真正提交的是cascadeId
<label for="CascadeName" class="control-label x120">父节点流水号:</label>
<input type="text" name="CascadeName" id="CascadeName"
data-toggle="selectztree" size="20" data-tree="#j_select_tree1" value="">
<ul id="j_select_tree1" class="ztree hide" data-toggle="ztree"></ul>
<script type="text/javascript">
$(document).ready(function () {
Init();
});
function Init() {
var setting = {
view: {
selectedMulti: false
},
check: {
enable: true,
chkStyle: "radio",
radioType: "all"
},
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {
onClick: zTreeOnClick,
onCheck: zTreeCheck
}
};
$.getJSON('CategoryManager/LoadForTree', function (json) {
var zTreeObj = $.fn.zTree.init($('#j_select_tree1'), setting, json);
zTreeObj.expandAll(true);
});
}
function zTreeCheck(e, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId),
nodes = zTree.getCheckedNodes(true);
var ids = '', names = '';
for (var i = 0; i < nodes.length; i++) {
ids += ',' + nodes[i].Id;
names += ',' + nodes[i].Name;
}
if (ids.length > 0) { //去掉第一个逗号
ids = ids.substr(1);
names = names.substr(1);
}
var $from = $('#' + treeId).data('fromObj');
if ($from && $from.length) $from.val(names);
$('#OrgId').val(ids);
}
function zTreeOnClick(event, treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj(treeId);
zTree.checkNode(treeNode, !treeNode.checked, true, true);
event.preventDefault();
}
</script>
}
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="bjui-pageFooter">
<ul>
<li><button type="button" class="btn-close">关闭</button></li>
<li><button type="submit" class="btn-green">保存</button></li>
</ul>
</div>

View File

@@ -0,0 +1,164 @@
@{
string _prefix = "Stock";
var _treeId = _prefix + "Tree";
var _gridId = _prefix + "Grid";
var _treeDetail = _prefix + "Detail";
}
@{ Html.RenderAction("MenuHeader", "Home");}
<div class="bjui-pageContent tableContent">
<div class="clearfix">
<div style="float: left; width: 220px; overflow: auto;" class="table table-bordered">
<ul id="@_treeId" class="ztree"></ul>
</div>
<div id="@_treeDetail" style="margin-left: 225px;">
</div>
</div>
</div>
<script type="text/javascript">
var selectedId = 0;
$(document).ready(function () {
initZtree();
loadDataGrid();
});
//加载数据到datagrid
function loadDataGrid() {
//b-jui的datagrid需要重新处理HTML
$('#@_treeDetail').empty()
.append('<table id="@_gridId" class="table table-bordered table-hover table-striped table-top"></table>');
$('#@_gridId').datagrid({
showToolbar: false,
filterThead: false,
columns: [
{
name: 'Id',
label: '数据ID',
width: 100
, hide: true
},
{
name: 'Name',
label: '产品名称',
width: 100
},
{
name: 'Number',
label: '产品数量',
width: 100
,type: 'select',
align: 'center',
items: [{ '0': '默认' }, { '1': '状态1' }],
},
{
name: 'Price',
label: '产品单价',
width: 100
},
{
name: 'Status',
label: '出库/入库',
width: 100
,type: 'select',
align: 'center',
items: [{ '0': '默认' }, { '1': '状态1' }],
},
{
name: 'User',
label: '',
width: 100
},
{
name: 'Time',
label: '操作时间',
width: 100
, type: 'date',
pattern: 'yyyy-MM-dd HH:mm:ss'
},
{
name: 'OrgId',
label: '组织ID',
width: 100
,type: 'select',
align: 'center',
items: [{ '0': '默认' }, { '1': '状态1' }],
},
],
dataUrl: 'StockManager/Load?parentId=' + selectedId,
fullGrid: true,
showLinenumber: true,
showCheckboxcol: true,
paging: true,
filterMult: false,
showTfoot: true,
height: '700'
});
}
function zTreeOnClick(event, treeId, treeNode) {
selectedId = treeNode.Id;
loadDataGrid();
}
function initZtree() {
var setting = {
view: {selectedMulti: false},
data: {
key: {
name: 'Name',
title: 'Name'
},
simpleData: {
enable: true,
idKey: 'Id',
pIdKey: 'ParentId',
rootPId: 'null'
}
},
callback: {onClick: zTreeOnClick}
};
$.getJSON('StockManager/LoadForTree', function (json) {
var zTreeObj = $.fn.zTree.init($('#@_treeId'), setting, json);
zTreeObj.expandAll(true);
});
}
//删除
function delStock() {
var selected = getSelected('#@_gridId',2);
if (selected == null) return;
$.getJSON('StockManager/Delete?Id=' + selected, function (data) {
if (data.statusCode == "200")
loadDataGrid();
else {
$(this).alertmsg('warn', data.message);
}
});
}
//自定义的编辑按钮
function editStock() {
var selected = getSelected('#@_gridId',2);
if (selected == null) return;
$(this).dialog({
id: 'editDialog',
url: '/StockManager/Add?id=' + selected,
title: '编辑',
onClose:function() {
refreshStockGrid();
}
});
}
function refreshStockGrid() {
$('#@_gridId').datagrid('refresh');
// loadDataGrid();
}
//@@ sourceURL=StockManagerIndex.js
</script>

View File

@@ -173,6 +173,22 @@
});
}
//用户可见组织授权按钮
function openUserOrgAccess(obj) {
var selected = getSelected('#@_gridId', 2);
if (selected == null) return;
$(obj).dialog({
id: 'accessUserOrg',
url: '/OrgManager/LookupMultiForUser',
title: '为用户分配可见部门',
data: {
userId: selected
}
});
}
//用户角色授权
function openUserRoleAccess(obj) {
var selected = getSelected('#@_gridId', 2);

View File

@@ -46,6 +46,7 @@
<component type=" OpenAuth.Repository.RelevanceRepository" service="OpenAuth.Domain.Interface.IRelevanceRepository,OpenAuth.Domain" />
<component type=" OpenAuth.Repository.CategoryRepository" service="OpenAuth.Domain.Interface.ICategoryRepository,OpenAuth.Domain" />
<component type=" OpenAuth.Repository.ResourceRepository" service="OpenAuth.Domain.Interface.IResourceRepository,OpenAuth.Domain" />
<component type=" OpenAuth.Repository.StockRepository" service="OpenAuth.Domain.Interface.IStockRepository,OpenAuth.Domain" />
</components>
</autofac>

View File

@@ -0,0 +1,55 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a CodeSmith Template.
//
// DO NOT MODIFY contents of this file. Changes to this
// file will be lost if the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace OpenAuth.Repository.Models.Mapping
{
public partial class StockMap
: System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<OpenAuth.Domain.Stock>
{
public StockMap()
{
// table
ToTable("Stock", "dbo");
// keys
HasKey(t => t.Id);
// Properties
Property(t => t.Id)
.HasColumnName("Id")
.IsRequired();
Property(t => t.Name)
.HasColumnName("Name")
.HasMaxLength(500)
.IsRequired();
Property(t => t.Number)
.HasColumnName("Number")
.IsRequired();
Property(t => t.Price)
.HasColumnName("Price")
.HasPrecision(10, 1)
.IsRequired();
Property(t => t.Status)
.HasColumnName("Status")
.IsRequired();
Property(t => t.User)
.HasColumnName("User")
.HasMaxLength(50)
.IsRequired();
Property(t => t.Time)
.HasColumnName("Time")
.IsRequired();
// Relationships
}
}
}

View File

@@ -16,7 +16,7 @@ namespace OpenAuth.Repository.Models.Mapping
.IsRequired()
.HasMaxLength(255);
this.Property(t => t.Phone_)
this.Property(t => t.Phone)
.IsRequired()
.HasMaxLength(255);
@@ -40,7 +40,7 @@ namespace OpenAuth.Repository.Models.Mapping
.IsRequired()
.HasMaxLength(255);
this.Property(t => t.QQ)
this.Property(t => t.Qq)
.IsRequired()
.HasMaxLength(255);
@@ -68,13 +68,13 @@ namespace OpenAuth.Repository.Models.Mapping
this.ToTable("UserExt");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.Phone_).HasColumnName("Phone_");
this.Property(t => t.Phone).HasColumnName("Phone_");
this.Property(t => t.Mobile).HasColumnName("Mobile");
this.Property(t => t.Address).HasColumnName("Address");
this.Property(t => t.Zip).HasColumnName("Zip");
this.Property(t => t.Birthday).HasColumnName("Birthday");
this.Property(t => t.IdCard).HasColumnName("IdCard");
this.Property(t => t.QQ).HasColumnName("QQ");
this.Property(t => t.Qq).HasColumnName("QQ");
this.Property(t => t.DynamicField).HasColumnName("DynamicField");
this.Property(t => t.ByteArrayId).HasColumnName("ByteArrayId");
this.Property(t => t.Remark).HasColumnName("Remark");

View File

@@ -31,6 +31,8 @@ namespace OpenAuth.Repository.Models
public DbSet<UserCfg> UserCfgs { get; set; }
public DbSet<UserExt> UserExts { get; set; }
public DbSet<Stock> Stocks { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
@@ -46,6 +48,8 @@ namespace OpenAuth.Repository.Models
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserCfgMap());
modelBuilder.Configurations.Add(new UserExtMap());
modelBuilder.Configurations.Add(new StockMap());
}
}
}

View File

@@ -66,6 +66,7 @@
<Compile Include="Models\Mapping\RelevanceMap.cs" />
<Compile Include="Models\Mapping\ResourceMap.cs" />
<Compile Include="Models\Mapping\RoleMap.cs" />
<Compile Include="Models\Mapping\StockMap.cs" />
<Compile Include="Models\Mapping\UserCfgMap.cs" />
<Compile Include="Models\Mapping\UserExtMap.cs" />
<Compile Include="Models\Mapping\UserMap.cs" />
@@ -76,6 +77,7 @@
<Compile Include="ResourceRepository.cs" />
<Compile Include="RoleRepository.cs" />
<Compile Include="CategoryRepository.cs" />
<Compile Include="StockRepository.cs" />
<Compile Include="UserRepository.cs" />
<Compile Include="RelevanceRepository.cs" />
</ItemGroup>
@@ -103,7 +105,6 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View File

@@ -0,0 +1,39 @@
using System.Collections.Generic;
using System.Linq;
using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
namespace OpenAuth.Repository
{
public class StockRepository :BaseRepository<Stock>, IStockRepository
{
public IEnumerable<Stock> LoadStocks(int pageindex, int pagesize)
{
return Context.Stocks.OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
}
public IEnumerable<Stock> LoadInOrgs(params int[] orgId)
{
var result = from stock in Context.Stocks where orgId.Contains(stock.Id)
select stock;
return result;
}
public int GetStockCntInOrgs(params int[] orgIds)
{
return LoadInOrgs(orgIds).Count();
}
public IEnumerable<Stock> LoadInOrgs(int pageindex, int pagesize, params int[] orgIds)
{
return LoadInOrgs(orgIds).OrderBy(u =>u.Id).Skip((pageindex -1)*pagesize).Take(pagesize);
}
public void Delete(int id)
{
Delete(u =>u.Id == id);
}
}
}

View File

@@ -23,7 +23,8 @@ namespace OpenAuth.UnitTest
new ModuleRepository(),
new RelevanceRepository(),
new BaseRepository<ModuleElement>(),
new ResourceRepository()
new ResourceRepository(),
new OrgRepository()
);
var user = login.Login("admin", "admin");
foreach (var module in user.Modules)

View File

@@ -17,7 +17,7 @@ namespace OpenAuth.UnitTest
{
private TestContext testContextInstance;
private OrgManagerApp _app = new OrgManagerApp(new OrgRepository());
private OrgManagerApp _app = new OrgManagerApp(new OrgRepository(), new RelevanceRepository());

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff