2017-03-07 179 views
0

所以,我一直在玩EF和Sqlite。我設法在我的開發環境中讓他們成功地讀寫數據庫中的「Hello world」。我正在使用像我說的實體框架和sqlite實體框架提供程序。如何正確實現一個帶有sqlite數據庫的WebAPI Web服務器?

我在閱讀EF需要在單線程環境中運行。這完全混淆了我,因爲據我瞭解,Web應用程序並行處理多個請求。一個需要單線程的實用程序如何可能希望在Web服務器中使用?

如果它的事項,下面是我用玩弄連接控制檯應用程序 - 它也代表了EF

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var context = new SessionContext("SessionTables.sqlite")) 
     { 
      var session = new Session() 
      { 
       SessionID = Guid.NewGuid().ToString("B"), 
       Domain = "NA", 
       Username = "Sidney", 
       Start = DateTime.UtcNow, 
      }; 
      context.Sessions.Add(session); 

      var action = new UserAction() 
      { 
       ActionDescription = "Tested Entity Framework", 
       OccurredAt = DateTime.UtcNow, 
      }; 
      session.Actions = new List<UserAction>(); 
      session.Actions.Add(action); 
      context.SaveChanges(); 
     } 
    } 
} 

public class Session 
{ 
    public string SessionID { get; set; } 
    public string Domain { get; set; } 
    public string Username { get; set; } 
    public DateTime Start { get; set; } 
    public DateTime End { get; set; } 
    public virtual ICollection<UserAction> Actions { get; set; } 
} 

public class UserAction 
{ 
    public int UserActionID { get; set; } 
    public string ActionDescription { get; set; } 
    public DateTime OccurredAt { get; set; } 
    public Guid SessionID { get; set; } 
    public virtual Session Session { get; set; } 
} 

class SessionContext : DbContext 
{ 
    public SessionContext(string filename) 
     : base(new SQLiteConnection() 
     { 
      ConnectionString = new SQLiteConnectionStringBuilder() 
      { 
       DataSource = filename, ForeignKeys = true 
      } 
     .ConnectionString 
     }, true) 
    { /**/ } 

    public DbSet<Session> Sessions { get; set; } 
    public DbSet<UserAction> Actions { get; set; } 
} 
+0

你的困惑與線程實例。話雖如此,你將擁有最多的連接數,所以你需要處理這個問題。 – Trey

+0

@Trey你是說我可以擁有多個DBContext對象實例,只要我不以一種交叉線程的方式與一個實例交互? – Sidney

+0

酷名btw,我也是:-)無論如何閱讀下面的答案。他釘了它。 – Trey

回答

2

這不應該是一個問題,我目前和經驗。來自NuGet的Microsoft.Data.Sqlite包含已經使用SQLITE_THREADSAFE = 1(序列化)編譯的SQLite版本。

儘管如此,EF似乎沒有任何問題,會使得應用程序應該是「單線程」。

請閱讀本文,解釋您將使用SQLite的唯一限制。正如文檔所述:

當使用SQLite提供程序時,您應該注意到許多限制。其中大部分是基於SQLite數據庫引擎的 中的限制的結果,並不特定於EF。

https://docs.microsoft.com/en-us/ef/core/providers/sqlite/limitations

相關問題