【问题标题】:How to Populate Custom Properties Tables When Using SimpleMembership in ASP.NET MVC 4在 ASP.NET MVC 4 中使用 SimpleMembership 时如何填充自定义属性表
【发布时间】:2013-03-11 07:30:19
【问题描述】:

我开始从事一个 MVC 项目,该项目具有 3 种类型的用户(客户、服务提供商和管理员),具有不同的特定属性。我想在 Visual Studio 2012 的 ASP.NET MVC Web Application Internet Application 模板中扩展默认的 SimpleMembership 实现。

我有 Customer 类(不确定 Key 属性和关系)

public class Customer
{
    [Key]
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }

    public virtual UserProfile UserProfile { get; set; }
}

并在 SQL Server Express 中拥有 Customer 表:

CREATE TABLE [dbo].[Customer]
(
    [UserName] NVARCHAR(MAX) NOT NULL, 
    [FirstName] NVARCHAR(50) NOT NULL, 
    [LastName] NVARCHAR(50) NOT NULL, 
    [Phone] NVARCHAR(50) NULL
)

实体框架上下文:

public class UsersContext : DbContext
{
    public UsersContext() : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }

    public DbSet<Customer> Customers { get; set; }
}

我应该在下面添加什么代码来让 Customer 表与 UserProfile 表一起填充?

// Attempt to register the user
try
{
     WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

     WebSecurity.Login(model.UserName, model.Password);
     return RedirectToAction("Index", "Home");
 }

提前致谢

【问题讨论】:

    标签: entity-framework asp.net-mvc-4 simplemembership


    【解决方案1】:

    我从 Customer 类中删除了该行:

    public virtual UserProfile UserProfile { get; set; }
    

    客户类现在变为:

    public class Customer
    {
        [Key]
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
    }
    

    并将以下代码添加到 AccountController 的 Register 方法中:

    try
    {
         WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
    
         Customer cust = new Customer
         {
             UserName = model.UserName,
             FirstName = "Dikembe",
             LastName = "Mutombo",
             Phone = model.Phone
         };                  
         UsersContext context = new UsersContext();
         context.Customer.Add(cust);
         context.SaveChanges();
    
         WebSecurity.Login(model.UserName, model.Password);
         return RedirectToAction("Index", "Home");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 2019-10-28
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多