转移.net core 3.1,为.NET 5做准备

This commit is contained in:
ÂëÉñ
2020-10-22 14:59:36 +08:00
parent fd9bca23a7
commit a35d596237
1080 changed files with 175912 additions and 185681 deletions

View File

@@ -1,7 +1,7 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Assembly Src="../Internal/Model.cs" %>
<%@ Assembly Src="../Internal/Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
@@ -10,87 +10,72 @@
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="EntityContext" Type="SchemaMapper.EntityContext" %>
<%@ Property Name="WholeDb"
Type="System.Boolean"
Category="1.Database"
Default="true"
Description="是否为整个数据库" %>
<%@ Property Name="SourceDatabase"
Type="SchemaExplorer.DatabaseSchema"
Category="1.Database"
Description="The source database." %>
<%@ Property Name="SourceTables"
Type="SchemaExplorer.TableSchemaCollection"
Category="1.Database" Description="选择部分表" %>
<%@ 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 Microsoft.EntityFrameworkCore;
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);
<%
string dbContextName;
if(WholeDb){
dbContextName = SourceDatabase.Name.ToSafeName();
}
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)
else{
dbContextName = SourceTables.First().Database.Name.ToSafeName();
}
dbContextName = StringUtil.ToPascalCase(dbContextName);
Response.WriteLine(" public partial class "+ dbContextName +"Context: DbContext");
%>
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
<% foreach(var p in EntityContext.Entities) { %>
modelBuilder.Configurations.Add(new <%= p.MappingName.ToSafeName() %>());
<% } // foreach %>
//当主键为联合主键时,需要把这里的内容拷贝到对应的位置
<%
TableSchemaCollection tables;
if(WholeDb){
tables = SourceDatabase.Tables;
}
else{
tables = SourceTables;
}
// InitializeMapping(modelBuilder);
foreach(TableSchema table in tables)
{
if(table.PrimaryKeys.Count <=1) continue;
var keys = string.Join(",", table.Columns.Where(u=>u.IsPrimaryKeyMember==true)
.Select(u =>"c."+u.Name));
Response.WriteLine(" modelBuilder.Entity<"+table.Name+">()");
Response.WriteLine(" .HasKey(c => new { "+keys+" });");
}
%>
}
<% if (InterfaceMode) { %>
System.Data.Entity.IDbSet<TEntity> IDbContext.Set<TEntity>()
<%
foreach(TableSchema table in tables)
{
return base.Set<TEntity>();
Response.WriteLine(" public virtual DbSet<"+table.Name+"> "+StringUtil.ToPascalCase(StringUtil.ToPlural(table.Name))+" { get; set; }");
}
<% } // if interface %>
%>
}
}

View File

@@ -1,7 +1,7 @@
<%@ Template Language="C#" TargetLanguage="C#" Debug="True" Encoding="UTF-8" %>
<%@ Assembly Src="Model.cs" %>
<%@ Assembly Src="Extensions.cs" %>
<%@ Assembly Src="../Internal/Model.cs" %>
<%@ Assembly Src="../Internal/Extensions.cs" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
@@ -10,8 +10,8 @@
<%@ Import Namespace="SchemaMapper" %>
<%@ Property Name="Entity"
Type="SchemaMapper.Entity" %>
<%@ Property Name="Table"
Type="SchemaExplorer.TableSchema" %>
<%@ Property Name="EntityNamespace"
Type="System.String" %>
@@ -26,47 +26,50 @@
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using OpenAuth.Repository.Core;
namespace <%= EntityNamespace %>
{
/// <summary>
/// <%= Entity.Description %>
/// <%= Table.Description %>
/// </summary>
public partial class <%= Entity.ClassName.ToSafeName() %> : Entity
[Table("<%= Table.Name%>")]
public partial class <%= Table.Name %> : Entity
{
public <%= Entity.ClassName.ToSafeName() %>()
public <%= Table.Name %>()
{
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
string type = p.SystemType.ToNullableType(p.IsNullable == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.PropertyName.ToSafeName()+"= DateTime.Now;");
} // foreach %>
<% foreach(var r in Entity.Relationships.Where(e => e.ThisCardinality == Cardinality.Many)) { %>
<%= r.ThisPropertyName.ToSafeName() %> = new List<<%= r.OtherEntity.ToSafeName() %>>();
<% } // foreach %>
<% foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
string type = p.SystemType.ToNullableType(p.AllowDBNull == true);
if(type =="int" || type=="decimal")
Response.WriteLine(" this."+p.Name+"= 0;");
else if(type =="string")
Response.WriteLine(" this."+p.Name+"= string.Empty;");
else if(type.ToLower().Contains("datetime"))
Response.WriteLine(" this."+p.Name+"= DateTime.Now;");
} // foreach %>
}
<% foreach(var p in Entity.Properties) {
if(p.IsPrimaryKey ==true) continue;
%>
<%
foreach(ColumnSchema p in Table.Columns) {
if(p.IsPrimaryKeyMember) continue;
%>
/// <summary>
/// <%=p.Description %>
/// </summary>
public <%= p.SystemType.ToNullableType(p.IsNullable == true) %> <%= p.PropertyName.ToSafeName() %> { get; set; }
<% } // foreach %>
<% foreach(var r in Entity.Relationships) { %>
<% if(r.ThisCardinality == Cardinality.Many) { %>
public virtual ICollection<<%= r.OtherEntity.ToSafeName() %>> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } else { %>
public virtual <%= r.OtherEntity.ToSafeName() %> <%= r.ThisPropertyName.ToSafeName() %> { get; set; }
<% } %>
<% } // foreach %>
/// <%=p.Description %>
/// </summary>
[Description("<%=p.Description%>")]
<%if(p.Name.LastIndexOf("Id") != -1){%>
[Browsable(false)]
<%}%>
<%if(p.DataType == DbType.Byte){%>
public bool <%= p.Name%> { get; set; }
<%}else{%>
public <%= p.SystemType.ToNullableType(p.AllowDBNull == true) %> <%= p.Name%> { get; set; }
<%}%>
<% } // foreach %>
}
}

View File

@@ -205,6 +205,27 @@ namespace SchemaMapper
get { return _settings; }
}
//按表信息创建DbContext
public EntityContext Generate(TableSchema tableSchema)
{
// only DeepLoad when in ignore mode
tableSchema.DeepLoad = !Settings.InclusionMode;
var entityContext = new EntityContext();
entityContext.DatabaseName = tableSchema.Database.Name;
string dataContextName = StringUtil.ToPascalCase(tableSchema.Database.Name) + "Context";
dataContextName = _namer.UniqueClassName(dataContextName);
entityContext.ClassName = dataContextName;
GetEntity(entityContext, tableSchema);
return entityContext;
}
//按数据库连接信息创建DbContext
public EntityContext Generate(DatabaseSchema databaseSchema)
{
// only DeepLoad when in ignore mode
@@ -240,8 +261,8 @@ namespace SchemaMapper
return entityContext;
}
private Entity GetEntity(EntityContext entityContext, TableSchema tableSchema, bool processRelationships = true, bool processMethods = true)
//根据DbContext和tableSchema获取实体
public Entity GetEntity(EntityContext entityContext, TableSchema tableSchema, bool processRelationships = true, bool processMethods = true)
{
string key = tableSchema.FullName;
@@ -363,7 +384,7 @@ namespace SchemaMapper
if (Settings.IsIgnored(tableKey.ForeignKeyTable.FullName)
|| Settings.IsIgnored(tableKey.PrimaryKeyTable.FullName))
{
Debug.WriteLine("Skipping relationship '{0}' because table '{1}' or '{2}' is ignored.",
Debug.WriteLine("Skipping relationship '{0}' because table '{1}' or '{2}' is ignored.",
tableKey.FullName, tableKey.ForeignKeyTable.FullName, tableKey.PrimaryKeyTable.FullName);
continue;

View File

@@ -1,294 +0,0 @@
<%@ 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>