C# dbml 反转为表结构
2022/1/20 11:41:47
本文主要是介绍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 反转为表结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具