2016-11-09 181 views
1

我在我的項目中使用了ORM。目前種子數據是從SQL腳本中獲取的,但我想根據我的C#代碼創建種子數據。例如,我有SQL:從sql腳本創建種子數據

SET IDENTITY_INSERT [dbo].[State] ON 
INSERT INTO [dbo].[State] ([Id], [Code], [Name]) VALUES (1, N'AL', N'Alabama') 
INSERT INTO [dbo].[State] ([Id], [Code], [Name]) VALUES (2, N'AK', N'Alaska') 
SET IDENTITY_INSERT [dbo].[State] OFF 

,取而代之的是我想有一個字符串:

new List<State> 
{ 
    new State { Id = 1, Code = "AL", Name = "Alabama" }, 
    new State { Id = 2, Code = "AK", Name = "Alaska" } 
}; 

我怎樣才能實現呢?

回答

1

對於INSERT語句(如你所說,你需要的種子),可以創建helper方法是這樣的:

public static List<State> ParseSqlScript(string sqlScriptPath) 
    { 
     using (var reader = new StreamReader(sqlScriptPath)) 
     { 
      var sqlScript = reader.ReadToEnd(); 
      var pattern = @"INSERT INTO \[dbo\].\[State\] \(\[Id\], \[Code\], \[Name\]\) VALUES (\(.*?\))"; 
      var regex = new Regex(pattern); 
      var matches = regex.Matches(sqlScript); 
      var states = new List<State>(); 
      foreach (Match match in matches) 
      { 
       var values = match.Groups[1].Value.Split(new [] { '(', ',',' ',')' }, StringSplitOptions.RemoveEmptyEntries); 
       var id = int.Parse(values[0]); 
       var code = values[1].Substring(2, values[1].Length - 3); 
       var name = values[2].Substring(2, values[2].Length - 3); 
       foreach (var value in values) 
       { 
        var state = new State() { Id = id, Code = code, Name = name }; 
        states.Add(state); 
       } 
      } 

      return states; 
     } 
    } 

如果您還需要您可能需要獲得一些SQL解析器熟悉其他CRUD語句,也許Microsoft.SqlServer.SMO。

+0

獲得'列表狀態'多少感謝!這正是我想要的。你節省了我的一天 –

0

嘗試添加如下代碼,我假設你與實體框架的工作:

List<State> states = new List<State>() 
      { 
       new State { Id = 1, Code = "AL", Name = "Alabama" }, 
       new State { Id = 2, Code = "AK", Name = "Alaska" } 

      }; 

StateDBEntities context = new StateDBEntities(); 
foreach (State state in states) 
      { 
       context.State.Add(state); 
      } 

      context.SaveChanges(); 
+0

謝謝你的回覆,但那不是我想要的。我的目標是從SQL腳本 –

0
List<State> states = new List<State>(); 

    using (SqlConnection connection = new SqlConnection("conn_string")) 
    { 
     string query = "SELECT Id, Code, Name FROM State"; 
     using (SqlCommand command = new SqlCommand(query, connection)) 
     { 
      using (SqlDataReader reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        State state = new State { Id = (int)reader["Id"], Code = reader["Code"].ToString(), Name = reader["Name"].ToString() }; 
        states.Add(state); 
       } 
      } 
     } 
    } 

調用Select查詢(在這裏我寫了查詢,但應該避免,你可以使用存儲過程)。使用ExecuteReader獲取所有列,並添加所有行以逐個列出。