gpt4 book ai didi

asp.net-mvc - 如何在 MVC 4 中使用我自己的 User 表而不是默认的 UserProfile?

转载 作者:行者123 更新时间:2023-12-02 03:53:08 25 4
gpt4 key购买 nike

我想创建大型用户表(高级用户配置文件)并将用户数据保存在我的数据库上下文中。所以,我不想在我的项目中使用 2 个 DbContext。当用户注册到站点时,他们的数据(用户名、密码等)存储我自己的用户表。我的类(class)是这样的:

public class ModelBase
{
public int Id { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
}

public class User : ModelBase
{
public string UserName { get; set; }
public string Password{ get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public DateTime BirthDate { get; set; }
public string Specialty { get; set; }
}

public class News : ModelBase
{
public int UserId { get; set; }
public string Title { get; set; }
...
}

....

上下文是这样的:

public class MyDBContext : DbContext
{
public MyDBContext()
{
Database.SetInitializer<MyDBContext>(new MyDBContextInitializer());
}

public DbSet<User> UserSet { get; set; }
public DbSet<News> NewsSet { get; set; }
public DbSet<Project> ProjectSet { get; set; }
public DbSet<Section> SectionSet { get; set; }
....
}

class MyDBContextInitializer : DropCreateDatabaseIfModelChanges<MyDBContext>
{
protected override void Seed(MyDBContext context)
{
base.Seed(context);
}
}

我用我的名称替换了 DbContext 名称,并在默认 SimpleMembershipInitializer 类中更改了连接名称,如下所示:

  ....
Database.SetInitializer<MyDBContext>(null);

try
{
using (var context = new MyDBContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}

WebSecurity.InitializeDatabaseConnection("MyDBContextConnection", "User", "Id", "UserName", autoCreateTables: true);
....

最后,我更改了适合我的用户类的 RegisterModelWebSecurity.CreateUserAndAccount()。但是,它不起作用。如何使用我自己的用户表注册网站?

最佳答案

您可以将 Asp.net Membership 和您的复杂类连接在一起。 使用这种方法,您将节省大量时间,因为 asp.net 成员资格更加强大(您无需考虑角色和用户管理),并且确保您可以利用现有的开源项目,如 this并以最少的时间将其添加到您的项目中。然后你的类(class)将有这样的结构:

public class CustomUserDetail : ModelBase
{
public string UserName { get; set; } // what you really need is this to be unique for each user in you data base
// public string Password{ get; set; } handled by asp.net Membership
public string FullName { get; set; }
// public string Email { get; set; } handled by asp.net Membership
public DateTime BirthDate { get; set; }
public string Specialty { get; set; }
}

然后你可以向 IPrincipal 添加扩展方法,例如:

public static CustomUserDetail CustomUserDetail (this IPrincipal principal)
{
var repository = new YourUserDetailRepository();
return repository.GetCurrentUserDetail();
}

最后在你的代码中轻松使用

<p> @User.CustomUserDetail.FullName  </p>

关于asp.net-mvc - 如何在 MVC 4 中使用我自己的 User 表而不是默认的 UserProfile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13696969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com