2012-04-19 49 views
0

我正在使用c#和System.Data.SQLite 我有一些類我想在運行時在SQLite中生成表,但我不想硬編碼每個類的SQL字符串。 我在想,做這件事的最好方法是什麼? 我嘗試添加希望會有一些會創建SQL字符串我,但屬性,我的階級和階級屬性... 下面是一個例子:有沒有辦法根據類定義在SQLite中動態生成表?

[Table(Name = "tblDocument")] 
    public class Document 
    { 
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] 
    public long DocumentId { get; set; } 

    [Column(CanBeNull = true)] 
    public string File { get; set; } 
    } 

要創建這個作爲SQLite的表,我需要生成類似的東西:

string CreateSqlString = 
    @"CREATE TABLE [tblDocument] (" + 
    @"[DocumentId] INTEGER PRIMARY KEY NOT NULL," + 
    @"[File] TEXT NOT NULL)"; 

在此先感謝。

+0

有商業分貝sqlite的提供者,帶有EF/LINQ支持,可以做你想做的...如果這是你的選擇,我可以提供一個鏈接... – Yahia 2012-04-19 15:52:01

+0

我認爲System.Data.SQLite支持實體框架? 反正,我想要的可能會或可能不涉及EF,我真的不在乎使用的技術。 – 2012-04-19 19:31:03

回答

1

您是否在尋找類似於SubSonic的東西。它可以在啓用遷移的情況下運行,並且會爲您的類生成表。

假設你已經提到Castle.Core.dll,SubSonic.Core.dll和System.Data.SQLite.DLL

class Program 
{ 
    private const string ConnectionString = @"Data Source=c:\subsonic.db"; 
    private const string ProviderString = @"System.Data.SQLite"; 
    private static IDataProvider provider = ProviderFactory.GetProvider(ConnectionString, ProviderString); 
    private static SimpleRepository repo = new SimpleRepository(provider, SimpleRepositoryOptions.RunMigrations); 

    static void Main(string[] args) 
    { 
     var demo = new Demo { Name = "Test Demo", LaunchDate = DateTime.Now }; 
     repo.Add(demo); 
    } 

    class Demo 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public DateTime LaunchDate { get; set; } 
    } 
} 

的App.config應該

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <system.data> 
     <DbProviderFactories> 
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /> 
     </DbProviderFactories> 
    </system.data> 
</configuration> 
相關問題