的ApplicationContext
public class ApplicationContext : DbContext
{
public ApplicationContext() : base("name=DbConnection") { }
public virtual DbSet<Account> Accounts { get; set; }
public virtual DbSet<Credential> Credentials { get; set; }
}
WebConfig
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=DESKTOP-98TG6JE\SERVER_2014;Initial Catalog=SMBITS;User ID=sa;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
CreateAccountManager
private readonly SqlConnection _dbConnection;
private readonly ApplicationContext _context;
public CreateAccountManager()
{
_dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString);
_context = new ApplicationContext();
}
public string CreateAccount(CreateAccountViewModel account)
{
var result = "Failed in creating account";
if (UserNameExists(account.UserName))
return "Username is already taken";
using (var context = _context.Database.BeginTransaction())
{
try
{
var acct = new Account
{
FirstName = account.FirstName,
LastName = account.LastName,
MiddleName = account.MiddleName,
Status = "Active"
};
_context.Accounts.Add(acct);
_context.SaveChanges();
var credential = new Credential
{
AccountId = acct.AccountId,
Password = account.Password,
UserName = account.UserName
};
_context.Credentials.Add(credential);
_context.SaveChanges();
context.Commit();
result = "Successfully created the account";
}
catch
{
context.Rollback();
}
}
return result;
}
public bool UserNameExists(string username)
{
var result = false;
const string query = "SELECT CredentialId from credential where UserName = @UserName";
using (var cmd = new SqlCommand(query, _dbConnection))
{
try
{
cmd.Parameters.AddWithValue("@UserName", username);
_dbConnection.Open();
var rdr = cmd.ExecuteReader();
if (rdr.HasRows)
result = true;
}
catch
{
return true;
// ignore
}
finally
{
_dbConnection.Close();
}
}
return result;
}
运行代码时没有任何错误。 accountId递增,首先它是1然后是2然后是3然后是4,这意味着它正在保存(据我所知)。但是,当我检查Web配置中声明的数据库时,我看不到插入的数据。此外,我有一种感觉,数据正在保存,但可能会被保存到另一个数据库,因为即使我一次又一次地使用相同的用户名,我总是得到假,意思是,它找不到重复。所以我猜它确实被保存在另一个数据库中。你能告诉我这个数据库的位置,以及如何将它指向正确的数据库。