Net Core教程

C# dbml 反转为表结构

本文主要是介绍C# dbml 反转为表结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

表结构丢失,但是dbml代码还在,可以通过反射将结构找回。但是注释及索引等信息丢失,需自己添加

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Linq.Mapping;
 4 using System.Linq;
 5 using System.Reflection;
 6 using System.Text;
 7 
 8 namespace TestSets
 9 {
10     public class TestForConvertDbmlToTable : TestBase
11     {
12         protected override string Title { get { return "测试 dbml反向生成数据库表格!"; } }
13 
14         public override void OnRunTest()
15         {
16             Console.WriteLine(ReverseDataTable.GenerateSqlScript(@"D:\Job\GDXX\WorkSpace\GDM\GDM.Linq\bin\Debug\GDM.Linq.dll"));
17         }
18     }
19 
20     public class ReverseDataTable
21     {
22         public static string GenerateSqlScript(string assemblyFullName)
23         {
24             var list = (from p in Assembly.LoadFile(assemblyFullName).GetTypes()
25                         let attrs = p.GetCustomAttributes(true)
26                         where attrs.Any(attr => attr is System.Data.Linq.Mapping.TableAttribute)
27                         select p).ToList()
28                         .Select(p => GenerateSqlCommondForCreateTable(p));
29             return string.Join(Environment.NewLine, list);
30         }
31 
32         private static string GenerateSqlCommondForCreateTable(Type classType)
33         {
34             var infoList = (from p in classType.GetProperties()
35                            let attr = p.GetCustomAttributes(true).OfType<ColumnAttribute>().FirstOrDefault()
36                            where attr != null
37                            select new
38                            {
39                                p.Name,
40                                attr,
41                            }).ToList();
42             // 存在属性CanBeNull=true,但是实际DbType为Not Null
43             // var fieldsInfo = infoList.Select(p => string.Format(" [{0}] {1} {2} ", p.Name, p.attr.DbType, p.attr.CanBeNull ? "NULL" : ""));
44             var fieldsInfo = infoList.Select(p => string.Format(" [{0}] {1} {2} ", p.Name, p.attr.DbType, !p.attr.DbType.ToUpper().Contains("NOT NULL") ? "NULL" : ""));
45 
46             var keyNames = infoList.Where(p => p.attr.IsPrimaryKey).Select(p => string.Format("[{0}] ASC ", p.Name)).ToList();
47             var keyCommondStr = string.Format("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED ({1})", classType.Name, string.Join(", ", keyNames))
48                                 + "WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]";
49 
50             return string.Format("CREATE TABLE {0} ({1} {2})", classType.Name, string.Join(", ", fieldsInfo), keyCommondStr);
51         }
52     }
53 
54 }

 

这篇关于C# dbml 反转为表结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!