Linq批量建表
public JsonResult CreateTable() { db = new RZBDbContext(); var query = (from c in db.Clients select new { pre = c.Prefix }).ToList(); foreach (var d in query) { //遍历循环client 生成表 //创建数据表 var file = Server.MapPath("~/App_Data/create_log.sql"); var sql = System.IO.File.ReadAllText(file); sql = sql.Replace("{t}", d.pre); db.Database.ExecuteSqlCommand(sql); _log.Info("建立表:"+ d.pre+"_Log"); //Thread.Sleep(1000); } ResultModel model = new ResultModel(); model.StrMessage = "Welcome"; return Json(model, JsonRequestBehavior.AllowGet); }
sql文件:
CREATE TABLE [{t}_QueryLog]( [ID] [uniqueidentifier] NOT NULL, [LoginUserID] [uniqueidentifier] NOT NULL, [IdentityID] [nvarchar](50) NOT NULL, [IdentityName] [nvarchar](200) NOT NULL, [QueryTime] [datetime] NOT NULL, [IsHistory] [bit] NOT NULL, [IsCharge] [bit] NOT NULL, [IsSimpleCheck] [bit] NOT NULL, [ext1] [nvarchar](50) NULL, [ext2] [nvarchar](50) NULL, [CreateUser] [nvarchar](50) NULL, [CreateTime] [datetime] NULL, [UpdateUser] [nvarchar](50) NULL, [UpdateTime] [datetime] NULL ) ON [PRIMARY] ; /****** Object: Index [IX_{t}_QueryLog_IdentityID] Script Date: 03/06/2014 11:07:13 ******/ CREATE NONCLUSTERED INDEX [IX_{t}_QueryLog_IdentityID] ON [dbo].[{t}_QueryLog] ( [IdentityID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ; /****** Object: Index [IX_{t}_QueryLog_IdentityName] Script Date: 03/06/2014 11:07:13 ******/ CREATE NONCLUSTERED INDEX [IX_{t}_QueryLog_IdentityName] ON [dbo].[{t}_QueryLog] ( [IdentityName] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ; /****** Object: Index [IX_{t}_QueryLog_QueryTime] Script Date: 03/06/2014 11:07:13 ******/ CREATE NONCLUSTERED INDEX [IX_{t}_QueryLog_QueryTime] ON [dbo].[{t}_QueryLog] ( [QueryTime] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_ID] DEFAULT (newid()) FOR [ID] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_QueryTime] DEFAULT (getdate()) FOR [QueryTime] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_IsHistory] DEFAULT ((0)) FOR [IsHistory] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_IsCharge] DEFAULT ((1)) FOR [IsCharge] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_IsSimpleCheck] DEFAULT ((1)) FOR [IsSimpleCheck] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_CreateTime] DEFAULT (getdate()) FOR [CreateTime] ; ALTER TABLE [dbo].[{t}_QueryLog] ADD CONSTRAINT [DF_{t}_QueryLog_UpdateTime] DEFAULT (getdate()) FOR [UpdateTime] ;