This commit is contained in:
sunkaixuan
2019-01-21 16:47:00 +08:00
parent 1161ae7a61
commit 5689adedd4
17 changed files with 0 additions and 866 deletions

View File

@@ -1,8 +0,0 @@
namespace SugarCodeGeneration
{
public class BLLParameter
{
public string Name { get; set; }
public string ClassNamespace { get; set; }
}
}

View File

@@ -1,13 +0,0 @@
using System.Collections.Generic;
using SqlSugar;
namespace SugarCodeGeneration
{
public class DbContextParameter
{
public string ConnectionString { get; set; }
public DbType DbType { get; set; }
public List<string> Tables { get; set; }
public string ClassNamespace { get; set; }
}
}

View File

@@ -1,70 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SugarCodeGeneration.Codes
{
internal class FileHelper
{
public static void CreateFile(string filePath, string text, Encoding encoding)
{
try
{
if (IsExistFile(filePath))
{
DeleteFile(filePath);
}
if (!IsExistFile(filePath))
{
string directoryPath = GetDirectoryFromFilePath(filePath);
CreateDirectory(directoryPath);
//Create File
FileInfo file = new FileInfo(filePath);
using (FileStream stream = file.Create())
{
using (StreamWriter writer = new StreamWriter(stream, encoding))
{
writer.Write(text);
writer.Flush();
}
}
}
}
catch(Exception ex)
{
throw ex;
}
}
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
public static void CreateDirectory(string directoryPath)
{
if (!IsExistDirectory(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
public static void DeleteFile(string filePath)
{
if (IsExistFile(filePath))
{
File.Delete(filePath);
}
}
public static string GetDirectoryFromFilePath(string filePath)
{
FileInfo file = new FileInfo(filePath);
DirectoryInfo directory = file.Directory;
return directory.FullName;
}
public static bool IsExistFile(string filePath)
{
return File.Exists(filePath);
}
}
}

View File

@@ -1,168 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using RazorEngine;
using RazorEngine.Templating;
namespace SugarCodeGeneration.Codes
{
/// <summary>
/// 生成所需要的代码
/// </summary>
public class Methods
{
public static Dictionary<string, string> ProjectIds = new Dictionary<string, string>();
public static string GetCurrentProjectPath
{
get
{
return Environment.CurrentDirectory.Replace(@"\bin\Debug", "");
}
}
public static string GetSlnPath
{
get
{
var path = Directory.GetParent(GetCurrentProjectPath).FullName;
return path;
}
}
public static void AddRef(string projectName, string refProjectName)
{
var xmlPath = GetSlnPath + @"\" + projectName + @"\" + projectName + ".csproj";
var xml = File.ReadAllText(xmlPath, System.Text.Encoding.UTF8);
if (xml.Contains(refProjectName)) return;
var firstLine = System.IO.File.ReadLines(xmlPath, System.Text.Encoding.UTF8).First();
var newXml = xml.Replace(firstLine, "").TrimStart('\r').TrimStart('\n');
XDocument xe = XDocument.Load(xmlPath);
var root = xe.Root;
XElement itemGroup = new XElement("ItemGroup");
var refItem = new XElement("ProjectReference", new XAttribute("Include", string.Format(@"..\{0}\{0}.csproj", refProjectName)));
refItem.Add(new XElement("Name", refProjectName));
refItem.Add(new XElement("Project", "{" + ProjectIds[refProjectName] + "}"));
itemGroup.Add(refItem);
root.Add(itemGroup);
newXml = xe.ToString().Replace("xmlns=\"\"", "");
xe = XDocument.Parse(newXml);
xe.Save(xmlPath);
}
public static void AddCsproj(string classPath, string projectName)
{
CreateProject(projectName);
var classDirectory = Methods.GetSlnPath + "\\" + projectName + "\\" + classPath.TrimStart('\\');
if (FileHelper.IsExistDirectory(classDirectory) == false)
{
FileHelper.CreateDirectory(classDirectory);
}
var files = Directory.GetFiles(classDirectory).ToList().Select(it => classPath + "\\" + Path.GetFileName(it));
var xmlPath = GetSlnPath + @"\" + projectName + @"\" + projectName + ".csproj";
var xml = File.ReadAllText(xmlPath, System.Text.Encoding.UTF8);
var firstLine = System.IO.File.ReadLines(xmlPath, System.Text.Encoding.UTF8).First();
var newXml = xml.Replace(firstLine, "").TrimStart('\r').TrimStart('\n');
XDocument xe = XDocument.Load(xmlPath);
var itemGroup = xe.Root.Elements().Where(it => it.Name.LocalName == "ItemGroup" && it.Elements().Any(y => y.Name.LocalName == "Compile")).First();
var compieList = itemGroup.Elements().ToList();
var noAddFiles = files.Where(it => !compieList.Any(f => it.Equals(f.Attribute("Include").Value, StringComparison.CurrentCultureIgnoreCase))).ToList();
if (noAddFiles.Any())
{
foreach (var item in noAddFiles)
{
var addItem = new XElement("Compile", new XAttribute("Include", item.TrimStart('\\')));
itemGroup.AddFirst(addItem);
}
}
newXml = xe.ToString().Replace("xmlns=\"\"", "");
xe = XDocument.Parse(newXml);
xe.Save(xmlPath);
}
public static void CreateBLL(string templatePath, string savePath, List<string> tables, string classNamespace)
{
string template = System.IO.File.ReadAllText(templatePath); //从文件中读出模板内容
string templateKey = "bll"; //取个名字
foreach (var item in tables)
{
BLLParameter model = new BLLParameter()
{
Name = item,
ClassNamespace = classNamespace
};
var result = Engine.Razor.RunCompile(template, templateKey, model.GetType(), model);
var cp = savePath + "\\" + item + "Manager.cs";
if (FileHelper.IsExistFile(cp) == false)
FileHelper.CreateFile(cp, result, System.Text.Encoding.UTF8);
}
}
public static void CreateDbContext(string templatePath, string savePath, object model)
{
string template = System.IO.File.ReadAllText(templatePath); //从文件中读出模板内容
string templateKey = "dbcontext"; //取个名字
var result = Engine.Razor.RunCompile(template, templateKey, model.GetType(), model);
FileHelper.CreateFile(savePath, result, System.Text.Encoding.UTF8);
}
public static void CreateProject(string name)
{
var templatePath = GetCurrentProjectPath + "/Template/Project.txt";
string projectId = Guid.NewGuid().ToString();
string project = System.IO.File.ReadAllText(templatePath).Replace("@pid", projectId).Replace("@AssemblyName", name); //从文件中读出模板内容
var projectPath = GetSlnPath + "\\" + name + "\\" + name + ".csproj";
var projectDic = GetSlnPath + "\\" + name + "\\";
var binDic = GetSlnPath + "\\" + name + "\\bin";
if (!FileHelper.IsExistFile(projectPath))
{
if (!FileHelper.IsExistDirectory(projectDic))
{
FileHelper.CreateDirectory(projectDic);
}
if (!FileHelper.IsExistDirectory(binDic))
{
FileHelper.CreateDirectory(binDic);
}
FileHelper.CreateFile(projectPath, project, System.Text.Encoding.UTF8);
FileHelper.CreateFile(projectDic + "\\class1.cs", "", System.Text.Encoding.UTF8);
//没成功File.Copy(GetCurrentProjectPath + "/Template/nuget.txt", projectDic + "packages.config");
ProjectIds.Add(name, projectId);
AppendProjectToSln(projectId, name);
}
}
public static void AppendProjectToSln(string projectId, string projectName)
{
var slns = Directory.GetFiles(GetSlnPath).Where(it => it.Contains(".sln"));
if (slns.Any())
{
var sln = slns.First();
var templatePath = GetCurrentProjectPath + "/Template/sln.txt";
string appendText = System.IO.File.ReadAllText(templatePath)
.Replace("@pid", projectId)
.Replace("@name", projectName)
.Replace("@sid", Guid.NewGuid().ToString());
FileStream fs = new FileStream(sln, FileMode.Append);
var sw = new StreamWriter(fs);
sw.WriteLine(appendText);
sw.Close();
fs.Close();
}
}
}
}

View File

@@ -1,171 +0,0 @@
using SugarCodeGeneration.Codes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace SugarCodeGeneration
{
class Program
{
//如果你不需要自定义直接配好数据库连接F5运行项目
const SqlSugar.DbType dbType = SqlSugar.DbType.SqlServer;
const string connectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SqlSugar4XTest";
static void Main(string[] args)
{
/***连接数据库***/
var db = GetDB();
/***生成实体***/
//配置参数
string classProjectName = "Sugar.Enties";//实体类项目名称
string classPath = "DbModels";//生成的目录
string classNamespace = "Sugar.Enties";//实体命名空间
var classDirectory = Methods.GetSlnPath + "\\" + classProjectName + "\\" + classPath.TrimStart('\\');
//执行生成
GenerationClass(classProjectName, classPath, classNamespace, classDirectory);
Print("实体创建成功");
/***生成DbContext***/
//配置参数
var contextProjectName = "Sugar.BusinessCore";//DbContext所在项目
var contextPath = "DbCore";//dbcontext存储目录
var savePath = Methods.GetSlnPath + "\\" + contextProjectName + "\\" + contextPath + "\\DbContext.cs";//具体文件名
var tables = db.DbMaintenance.GetTableInfoList().Select(it => it.Name).ToList();
//执行生成
GenerationDContext(contextProjectName, contextPath, savePath, tables, classNamespace);
Print("DbContext创建成功");
/***生成BLL***/
//配置参数
var bllProjectName2 = "Sugar.BusinessCore";//具体项目
var bllPath2 = "BaseCore";//文件目录
var savePath2 = Methods.GetSlnPath + "\\" + bllProjectName2 + "\\" + bllPath2;//保存目录
var tables2 = db.DbMaintenance.GetTableInfoList().Select(it => it.Name).ToList();
//执行生成
GenerationBLL(bllProjectName2,bllPath2,savePath2, tables2, classNamespace);
Print("BLL创建成功");
/***修改解决方案***/
UpdateCsproj();
Print("项目解决方案修改成功");
/***添加项目引用***/
Methods.AddRef(bllProjectName2,classProjectName);
Print("引用添加成功");
//如何使用创建好的业务类(注意 SchoolManager 不能是静态的)
//SchoolManager sm = new SchoolManager();
//sm.GetList();
//sm.StudentDb.AsQueryable().Where(it => it.Id == 1).ToList();
//sm.Db.Queryable<Student>().ToList();
}
/// <summary>
/// 生成BLL
/// </summary>
private static void GenerationBLL(string bllProjectName, string bllPath, string savePath, List<string>tables,string classNamespace)
{
var templatePath = Methods.GetCurrentProjectPath + "\\Template\\Bll.txt";//bll模版地址
//下面代码不动
Methods.CreateBLL(templatePath, savePath, tables, classNamespace);
AddTask(bllProjectName, bllPath);
}
/// <summary>
/// 生成DbContext
/// </summary>
private static void GenerationDContext(string contextProjectName, string contextPath, string savePath,List<string> tables,string classNamespace)
{
var templatePath = Methods.GetCurrentProjectPath + "\\Template\\DbContext.txt";//dbcontexts模版文件
//下面代码不动
var model = new DbContextParameter{
ConnectionString = connectionString,
DbType = dbType,
Tables = tables,
ClassNamespace= classNamespace
};
Methods.CreateDbContext(templatePath,savePath,model);
AddTask(contextProjectName,contextPath);
}
/// <summary>
/// 生成实体类
/// </summary>
private static void GenerationClass(string classProjectName,string classPath,string classNamespace,string classDirectory)
{
//连接数据库
var db = GetDB();
//下面代码不动
db.DbFirst.IsCreateAttribute().CreateClassFile(classDirectory, classNamespace);
AddTask(classProjectName,classPath);
}
#region
/// <summary>
/// 修改解决方案
/// </summary>
private static void UpdateCsproj()
{
foreach (var item in CsprojList)
{
item.Start();
item.Wait();
}
}
private static void Print(string message)
{
Console.WriteLine("");
Console.WriteLine(message);
Console.WriteLine("");
}
private static void AddTask(string bllProjectName, string bllPath)
{
var task = new Task(() =>
{
Methods.AddCsproj(bllPath, bllProjectName);
});
CsprojList.Add(task);
}
static List<Task> CsprojList = new List<Task>();
static SqlSugar.SqlSugarClient GetDB()
{
return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
{
DbType = dbType,
ConnectionString = connectionString,
IsAutoCloseConnection = true,
InitKeyType = SqlSugar.InitKeyType.Attribute
});
}
#endregion
}
}

View File

@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SugarCodeGeneration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SugarCodeGeneration")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("d75c24a1-a76e-467e-bc2c-209297034795")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -1,98 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D75C24A1-A76E-467E-BC2C-209297034795}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>SugarCodeGeneration</RootNamespace>
<AssemblyName>SugarCodeGeneration</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="MySql.Data, Version=6.7.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.6.7.9\lib\net40\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Oracle.ManagedDataAccess, Version=4.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=MSIL">
<HintPath>..\packages\Oracle.ManagedDataAccess.18.3.0\lib\net40\Oracle.ManagedDataAccess.dll</HintPath>
</Reference>
<Reference Include="RazorEngine, Version=3.10.0.0, Culture=neutral, PublicKeyToken=9ee697374c7e744a, processorArchitecture=MSIL">
<HintPath>..\packages\RazorEngine.3.10.0\lib\net40\RazorEngine.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="SqlSugar, Version=4.9.7.5, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\sqlSugar.4.9.7.5\lib\SqlSugar.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite, Version=1.0.102.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>xSqlite\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Razor.2.0.30506.0\lib\net40\System.Web.Razor.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Codes\BLLParameter.cs" />
<Compile Include="Codes\FileHelper.cs" />
<Compile Include="Codes\DbContextParameter.cs" />
<Compile Include="Codes\Methods.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Content Include="Template\BLL.txt" />
<Content Include="Template\DbContext.txt" />
<Content Include="Template\nuget.txt" />
<Content Include="Template\Project.txt" />
<Content Include="Template\sln.txt" />
<Content Include="x64\SQLite.Interop.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="x86\SQLite.Interop.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="xSqlite\System.Data.SQLite.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -1,85 +0,0 @@
using @Model.ClassNamespace;
using SqlSugar;
using System;
using System.Collections.Generic;
public class @(Model.Name)Manager : DbContext<@Model.Name>
{
//如果要修改生成的默认增删查改方法请修改SugarCodeGeneration项目下的BLL和DbContext模版
//我们如果有特殊需要可以重写DbContext中默认 增、删、查、改、方法
//这里面写的代码不会给覆盖,如果要重新生成请删除 MyOrderManager.cs
#region 教学方法
/// <summary>
/// 如果DbContext中的增删查改方法满足不了你你可以看下该方法的具体用法
/// </summary>
public void Study()
{
/*********查询*********/
var data1 = @(Model.Name)Db.GetById(1);//根据ID查询
var data2 = @(Model.Name)Db.GetList();//查询所有
var data3 = @(Model.Name)Db.GetList(it => 1 == 1); //根据条件查询
//var data4 = @(Model.Name)Db.GetSingle(it => 1 == 1);//根据条件查询一条,如果超过一条会报错
var p = new PageModel() { PageIndex = 1, PageSize = 2 };// 分页查询
var data5 = @(Model.Name)Db.GetPageList(it => 1 == 1, p);
Console.Write(p.PageCount);//返回总数
var data6 = @(Model.Name)Db.GetPageList(it => 1 == 1, p, it => SqlFunc.GetRandom(), OrderByType.Asc);// 分页查询加排序
Console.Write(p.PageCount);//返回总数
List<IConditionalModel> conModels = new List<IConditionalModel>(); //组装条件查询作为条件实现 分页查询加排序
conModels.Add(new ConditionalModel() { FieldName = typeof(@Model.Name).GetProperties()[0].Name, ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
var data7 = @(Model.Name)Db.GetPageList(conModels, p, it => SqlFunc.GetRandom(), OrderByType.Asc);
@(Model.Name)Db.AsQueryable().Where(x => 1 == 1).ToList();//支持了转换成queryable,我们可以用queryable实现复杂功能
//我要用事务
var result = Db.Ado.UseTran(() =>
{
//写事务代码
});
if (result.IsSuccess)
{
//事务成功
}
//多表查询地址 http://www.codeisbug.com/Doc/8/1124
/*********插入*********/
var insertData = new @(Model.Name)() { };//测试参数
var insertArray = new @(Model.Name)[] { insertData };
@(Model.Name)Db.Insert(insertData);//插入
@(Model.Name)Db.InsertRange(insertArray);//批量插入
var id = @(Model.Name)Db.InsertReturnIdentity(insertData);//插入返回自增列
@(Model.Name)Db.AsInsertable(insertData).ExecuteCommand();//我们可以转成 Insertable实现复杂插入
/*********更新*********/
var updateData = new @(Model.Name)() { };//测试参数
var updateArray = new @(Model.Name)[] { updateData };//测试参数
@(Model.Name)Db.Update(updateData);//根据实体更新
@(Model.Name)Db.UpdateRange(updateArray);//批量更新
//@(Model.Name)Db.Update(it => new @(Model.Name)() { Name = "a", CreateTime = DateTime.Now }, it => it.id==1);// 只更新Name列和CreateTime列其它列不更新条件id=1
@(Model.Name)Db.AsUpdateable(updateData).ExecuteCommand();
/*********删除*********/
var deldata = new @(Model.Name)() { };//测试参数
@(Model.Name)Db.Delete(deldata);//根据实体删除
@(Model.Name)Db.DeleteById(1);//根据主键删除
@(Model.Name)Db.DeleteById(new int[] { 1,2});//根据主键数组删除
@(Model.Name)Db.Delete(it=>1==2);//根据条件删除
@(Model.Name)Db.AsDeleteable().Where(it=>1==2).ExecuteCommand();//转成Deleteable实现复杂的操作
}
#endregion
}

View File

@@ -1,80 +0,0 @@
using @Model.ClassNamespace;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
public class DbContext<T> where T : class, new()
{
public DbContext()
{
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "@Model.ConnectionString",
DbType = DbType.@Model.DbType,
InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
});
//调式代码 用来打印SQL
Db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" +
Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
Console.WriteLine();
};
}
//注意:不能写成静态的
public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }
@foreach(var item in @Model.Tables)
{
@: public SimpleClient<@item> @(item)Db { get { return new SimpleClient<@item>(Db); } }//用来处理Student表的常用操作
}
/// <summary>
/// 获取所有
/// </summary>
/// <returns></returns>
public virtual List<T> GetList()
{
return CurrentDb.GetList();
}
/// <summary>
/// 根据主键删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual bool Delete(dynamic id)
{
return CurrentDb.Delete(id);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual bool Update(T obj)
{
return CurrentDb.Update(obj);
}
/// <summary>
/// 插入
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual bool Insert(T obj)
{
return CurrentDb.Insert(obj);
}
//自已扩展更多方法
}

View File

@@ -1,64 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="11.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>@pid</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>@AssemblyName</RootNamespace>
<AssemblyName>@AssemblyName</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="SqlSugar">
<HintPath>..\SugarCodeGeneration\bin\Debug\SqlSugar.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Reference Include="System"/>
<Reference Include="System.Core"/>
<Reference Include="System.Xml.Linq"/>
<Reference Include="System.Data.DataSetExtensions"/>
<Reference Include="Microsoft.CSharp"/>
<Reference Include="System.Data"/>
<Reference Include="System.Xml"/>
</ItemGroup>
<ItemGroup>
<Compile Include="Class1.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.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">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="MySql.Data" version="6.7.9" targetFramework="net40" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" />
<package id="Oracle.ManagedDataAccess" version="18.3.0" targetFramework="net40" />
<package id="RazorEngine" version="3.10.0" targetFramework="net40" />
<package id="sqlSugar" version="4.9.7.5" targetFramework="net40" />
</packages>

View File

@@ -1,3 +0,0 @@

Project("{@pid}") = "@name", "@name\@name.csproj", "{@sid}"
EndProject

View File

@@ -1,53 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.7.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.18.3, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.7.9.0" newVersion="6.7.9.0" />
</dependentAssembly>
<dependentAssembly>
<publisherPolicy apply="no" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.122.18.3" newVersion="4.122.18.3" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.109.0" newVersion="1.0.109.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
</configuration>

View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.Razor" version="2.0.30506.0" targetFramework="net40" />
<package id="MySql.Data" version="6.7.9" targetFramework="net40" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" />
<package id="Oracle.ManagedDataAccess" version="18.3.0" targetFramework="net40" />
<package id="RazorEngine" version="3.10.0" targetFramework="net40" />
<package id="sqlSugar" version="4.9.7.5" targetFramework="net40" />
</packages>