上一遍我介绍了如何使用引用对象的方法,这一篇我介绍一个工具,用来专门生成上一篇中各个实体类的对应部分类:不多说,直接上代码:
class Program
{
static void Main(string[] args)
{
foreach (var fileName in System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory))
{
if (fileName.ToLower().EndsWith(".dll"))
{
Assembly assembly = Assembly.LoadFile(fileName);
EdmRelationshipAttribute[] atrrs = (EdmRelationshipAttribute[])Attribute.GetCustomAttributes(assembly, typeof(EdmRelationshipAttribute));
string newFoldeName = fileName.Remove(fileName.LastIndexOf('.')) + "PartialClass";
var directInfo = System.IO.Directory.CreateDirectory(newFoldeName);
//获取程序集的命名空间
string namespa = (fileName.Replace(AppDomain.CurrentDomain.BaseDirectory, ""));
namespa = namespa.Remove(namespa.LastIndexOf('.'));
foreach (var type in assembly.GetTypes())
{
if (type.IsSubclassOf(typeof(System.Data.Objects.DataClasses.EntityObject)))
{
StringBuilder strBuild = new StringBuilder();
strBuild.Append(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;");
strBuild.AppendLine();
strBuild.AppendLine("namespace " + namespa);
strBuild.AppendLine("{");
strBuild.AppendLine("\t#region " + type.Name);
strBuild.AppendLine("\tpublic partial class " + type.Name);
strBuild.AppendLine("\t{");
if (atrrs != null)
{
foreach (var r in atrrs)
{
if (r.Role2Type == type)
{
//添加注释
strBuild.AppendLine("\t\t/// <summary>");
strBuild.AppendLine("\t\t/// 获取" + r.Role1Type.Name);
strBuild.AppendLine("\t\t/// </summary>");
//添加方法
strBuild.AppendLine("\t\tpublic " + r.Role1Type.Name + " Get" + r.Role1Type.Name + "()");
strBuild.AppendLine("\t\t{");
strBuild.AppendLine("\t\t\tif (this." + r.Role1Type.Name + " == null)");
strBuild.AppendLine("\t\t\t\tthis." + r.Role1Type.Name + "Reference.Load();");
strBuild.AppendLine("\t\t\t return this." + r.Role1Type.Name + ";");
strBuild.AppendLine("\t\t}");
}
}
}
strBuild.AppendLine("\t}");
strBuild.AppendLine("\t#endregion");
strBuild.AppendLine();
strBuild.AppendLine("}");
using (var stream = System.IO.File.Create(System.IO.Path.Combine(directInfo.Name, type.Name + ".PartialClass.cs")))
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuild.ToString());
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
}
}
}
}
}
}
使用方法是,直接将实体框架的实体类项目编译成dll,然后将dll放在本工具的同级目录下就可以了