【发布时间】:2018-08-22 09:32:46
【问题描述】:
我想为我的应用程序连接 SQL Server 数据库。我想提供两种身份验证,一种是windows身份验证,另一种是Sql server身份验证。我试过下面的代码。但是,我很困惑我的文件实际存储在哪里。
型号:
public class DataBase : PropertyChangedBase
{
public string Name { get; set; }
public DatabaseType DatabaseType { get; set; }
private AuthenticationType authenticationType;
public AuthenticationType AuthenticationType
{
get { return authenticationType; }
set
{
authenticationType = value;
NotifyOfPropertyChange(() => AuthenticationType);
}
}
public string UserName { get; set; }
public string Password { get; set; }
}
用于身份验证:
public void WindowsAuthentication(DataBase dataBase)
{
TaskContext = new TaskContext(dataBase.Name);
Tasks = GetAll();
}
public void ServerAuthentication(DataBase dataBase)
{
ConnectionString = string.Format("Data Source=.; User Id={0};Password={1};", dataBase.UserName, dataBase.Password);
try
{
SqlHelper = new SqlHelper(ConnectionString);
if (SqlHelper.IsConnection)
{
//AppSetting appSetting = new AppSetting();
//appSetting.SaveConnectionString("DbConnect", ConnectionString);
TaskContext = new TaskContext(ConnectionString);
Tasks = GetAll();
MessageBox.Show("Conected Successfully");
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Sql Server 连接检查:
public class SqlHelper
{
SqlConnection SqlConnection;
public SqlHelper(String connectionString)
{
SqlConnection = new SqlConnection(connectionString);
}
public bool IsConnection
{
get
{
if (SqlConnection.State == System.Data.ConnectionState.Closed)
SqlConnection.Open();
return true;
}
}
}
EF 代码:
public class TaskContext : DbContext
{
public TaskContext(string connection) : base(connection)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TaskContext>());
}
public DbSet<Task> Tasks { get; set; }
}
帮助我创建数据库并使用 EF 方法并存储在特定文件夹中
【问题讨论】:
-
默认文件位于 c:\Program Files 文件夹中。您可以使用 SQL Server Management Studio 来检查确切的位置,方法是右键单击数据库并选择属性:文件。
-
根据您使用的数据库服务器(SQLExpress、SQLServer、MySql 等),文件可能位于许多不同的位置。你没有说明你使用的是哪个 SQL 服务器,所以很难说。
-
使用 SQL Server 以及如何为 Windows 身份验证和 Sql server 身份验证提供连接字符串
标签: c# wpf entity-framework database-connection