【发布时间】:2015-02-09 16:23:39
【问题描述】:
我目前正在从事一个学习项目,在该项目中我曾经将表单身份验证与 sql 数据库一起使用。但是今天我已经更新为使用 Indetity。 我现在遇到的问题是我的网站存储的不仅仅是用户信息,我希望它与身份数据在同一个数据库中。 当我使用会员时,这没问题,我只是添加了一个连接字符串并编写了一条 SQL 语句。但现在看来我需要添加一些名为 DbContext 的东西? 也许看我的代码更容易理解,这是我的旧代码,用于旧的SQL数据库:
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO Website (url, rating, categoryId, subCategoryId, description1, description2) values (@url, @rating, @categoryId, @subCategoryId, @desc1, @desc2)";
cmd.Parameters.AddWithValue("@url", url);
cmd.Parameters.AddWithValue("@rating", rating);
cmd.Parameters.AddWithValue("@categoryId", categoryId);
cmd.Parameters.AddWithValue("@desc1", desc1);
cmd.Parameters.AddWithValue("@desc2", desc2);
if (DPLSubCategory.Items != null)
{
Int32 subCategoryId = Convert.ToInt32(DPLSubCategory.SelectedItem.Value);
cmd.Parameters.AddWithValue("@subCategoryId", subCategoryId);
}
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
现在假设我在本地身份数据库中添加了一个“网站”表。我怎样才能做与上面的代码类似的事情?现在我正在使用默认连接字符串:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\WDBAPP.mdf;Initial Catalog=WDBAPP;Integrated Security=True" providerName="System.Data.SqlClient"/>
我添加这样的成员:
// Default UserStore constructor uses the default connection string named: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
Response.Redirect("~/Login.aspx");
}
正如你所见,我不需要指向我的数据库,因为我使用了默认的连接字符串。
那么如何将我的连接字符串更改为例如“MyConString”并且仍然可以使用注册码?我希望能够从我的代码中指向我的数据库,以便我可以添加任何我想要的内容。
【问题讨论】:
-
您已经使用 Entity Framework 标记了您的问题,我建议您阅读该内容并做一两个教程。这可能比回答这个问题更有帮助。
-
我找到的所有教程都是针对 MVC 的。我使用网络表单。 Web 表单没有我可以找到和修改的 applicationdbcontext 类,我不知道如何创建。如果我错了,请纠正我@Win
-
我也尝试在 asp.net 论坛上寻求帮助。我不同意@Win 的观点,它是重复的,这个问题与我的不一样,甚至没有那么接近。也许我只是遗漏了一些明显的东西,只是因为“过时”的版本用 1 行代码完成的事情太复杂了。
标签: c# asp.net database entity-framework asp.net-identity