[英]Test connection to SQL Server with Entity Framework
在EntityFramework
以Code First
方式創建數據庫之前,我需要驗證Data Source
, UserId
和Password
。 那時,無法讀取任何數據以測試連接。 我的目標是為產品配置connectionString,並為用戶修改web.config
。 因此,我需要一種方法來驗證配置是否有效。 尤其是Data Source
,用戶UserId
和Password
的准確性。
因此,我希望測試SQL Server的連接,並且SQL Server可能根本沒有任何數據庫。 我需要測試有關Data Source
,用戶UserId
和Password
的連接能力。 如果某些參數無效,它將向用戶顯示錯誤消息。
因此,我需要以下功能。
Data Source
, UserId
和Password
由用戶輸入決定。 我用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
數據提供程序。 SqlConnection
是DbConnection
的子類,它接受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.