How to Populate Custom Properties Tables When Using SimpleMembership in ASP.NET MVC 4

谁说我不能喝 提交于 2019-12-08 08:12:19

问题


I started working on a MVC project which has 3 types of users (customers, service providers, and administrators) with different specific properties. I'd like to extend the default SimpleMembership implementation in ASP.NET MVC Web Application Internet Application template in Visual Studio 2012.

I have the Customer class (not sure about the Key attribute and the relationship)

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; }
}

and have the Customer table in SQL Server Express:

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

Entity Framework Context:

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

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

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

What code should I add below to get the Customer table populated along with the UserProfile table?

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

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

Thanks in advance


回答1:


I removed the line from the Customer class:

public virtual UserProfile UserProfile { get; set; }

The customer class now becomes:

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

and added the following code into the Register method of the AccountController:

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");
}


来源:https://stackoverflow.com/questions/15333324/how-to-populate-custom-properties-tables-when-using-simplemembership-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!