就个人而言,我建议不要使用 SQL Profile Provider(这是您正在使用的)。自 MVC2 以来,配置文件没有任何变化(或者,就此而言,因为它是在 .NET 2.0 的 Web 表单中引入的)。
原因是这样的:配置文件数据以 XML 形式存储在数据库中,这使得在您的应用程序之外使用配置文件数据非常困难(意味着在纯 SQL 查询中)。
直接在数据库中创建配置文件字段可能会好得多。这样您就知道数据来自哪个表/列,并且可以在需要时创建视图。否则,您将不得不解析表列的 XML 以提取配置文件数据(这是 ProfileCommon 在 .NET 中所做的)。
回复评论
首先,我对属性名称的理解是错误的。它是ProviderUserKey
,不是ProviderKey
。但是,除非您想为匿名用户存储配置文件属性,否则您可以像使用MembershipUser.UserName
FK 值一样轻松地使用它,因为它也是唯一的。
[HttpPost]
public ActionResult Register(RegisterModel model)
{
MembershipCreateStatus createStatus;
var membershipUser = Membership.CreateUser(model.UserName, model.Password,
model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
var providerKeyObject = membershipUser.ProviderUserKey;
var providerKeyGuid = (Guid)membershipUser.ProviderUserKey;
// Use providerKeyGuid as a foreign key when inserting into a profile
// table. You don't need a real db-level FK relationship between
// your profile table and the aspnet_Users table. You can lookup this
// Guid at any time by just getting the ProviderUserKey property of the
// MembershipUser, casting it to a Guid, and executing your SQL.
// Example using EF / DbContext
using (var db = new MyDbContext())
{
var profile = new MyProfileEntity
{
UserId = providerKeyGuid, // assumes this property is a Guid
FirstName = model.FirstName,
LastName = model.LastName,
};
db.Set<MyProfileEntity>().Add(profile);
db.SaveChanges();
}
// you could get the profile back out like this
using (var db = new MyDbContext())
{
var profile = db.Set<MyProfileEntity>().SingleOrDefault(p =>
p.UserId == (Guid)membershipUser.ProviderUserKey);
}
FormsAuthentication.SetAuthCookie(membershipUser.UserName, false);
return RedirectToAction("Index", "Home");
}
return View(model);
}
这是一个使用 UserName 而不是 ProviderUserKey 的示例。如果您不为匿名用户存储个人资料信息,我会推荐这种方法:
[HttpPost]
public ActionResult Register(RegisterModel model)
{
MembershipCreateStatus createStatus;
var membershipUser = Membership.CreateUser(model.UserName, model.Password,
model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
// Example using EF / DbContext
using (var db = new MyDbContext())
{
var profile = new MyProfileEntity
{
// assumes this property is a string, not a Guid
UserId = membershipUser.UserName,
FirstName = model.FirstName,
LastName = model.LastName,
};
db.Set<MyProfileEntity>().Add(profile);
db.SaveChanges();
}
// you could get the profile back out like this, but only after the
// auth cookie is written (it populates User.Identity.Name)
using (var db = new MyDbContext())
{
var profile = db.Set<MyProfileEntity>().SingleOrDefault(p =>
p.UserId == User.Identity.Name);
}
FormsAuthentication.SetAuthCookie(membershipUser.UserName, false);
return RedirectToAction("Index", "Home");
}
return View(model);
}