簡體   English   中英

使用實體框架測試與SQL Server的連接

[英]Test connection to SQL Server with Entity Framework

EntityFrameworkCode First方式創建數據庫之前,我需要驗證Data SourceUserIdPassword 那時,無法讀取任何數據以測試連接。 我的目標是為產品配置connectionString,並為用戶修改web.config 因此,我需要一種方法來驗證配置是否有效。 尤其是Data Source ,用戶UserIdPassword的准確性。

因此,我希望測試SQL Server的連接,並且SQL Server可能根本沒有任何數據庫。 我需要測試有關Data Source ,用戶UserIdPassword的連接能力。 如果某些參數無效,它將向用戶顯示錯誤消息。

因此,我需要以下功能。

  1. Data SourceUserIdPassword由用戶輸入決定。
  2. 沒有創建額外的數據庫。 如果創建了任何要測試的數據庫,則應在最后將其刪除。

樣本模型

我用EntityFramework編寫了一個簡單的Database model ,創建它用於測試 ,最后刪除數據庫。 connectionString由程序組成,因此TestDbContext應該接受DbConnection參數。

public class Test
{
    public long Id { get; set; }
    public string Field { get; set; }
}
public class TestDbContext : DbContext
{
    public DbSet<Test> TestSet { get; set; }

    public TestDbContext() {}
    /// For self-composed connection string.
    public TestDbContext(DbConnection conn) : base(conn, true) {}
}

撰寫連接字符串

然后, connectionString可以由SqlConnectionStringBuilder組成,該對象用於System.Data.SqlClient數據提供程序。 SqlConnectionDbConnection的子類,它接受sb生成的字符串。

SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
sb.DataSource = ...; //< The `Data Source` parameter
// The `InitialCatalog` parameter.
// Create an unique database for testing. And avoid name confliction.
sb.InitialCatalog = "testing" + Guid.NewGuid().ToString("N"); 
sb.UserID = ...; //< The `UserId`
sb.Password = ...; //< The `Password` of `UserId`.
sb.MultipleActiveResultSets = true;

SqlConnection dbConn = new SqlConnection(sb.ToString());

// dbConn.Open(); 
// It will be failed when the database had not been created.
// But, I need to verify the db server, account and password, 
// no matter whether the database is created or not.

測試連接

然后,通過EntityFramework測試連接。 非常方便。

// Test by self-composed connection string.
using (TestDbContext db = new TestDbContext(dbConn))
{
    // Create database. 
    // If failed to connect to the database server, it will throw an exception.
    db.Database.CreateIfNotExists();

    // Insert an item.
    var item = new Test() { Field="Hello World!!"};
    db.TestSet.Add(item);
    db.SaveChanges();

    // Delete database after testing
    db.Database.Delete();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM