1
votes

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

1 Answers

0
votes

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