我开始研究MVC项目,该项目有3种类型的用户(客户,服务提供商和管理员),具有不同的特定属性。我想在Visual Studio 2012中扩展ASP.NET MVC Web应用程序Internet应用程序模板中的默认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");
}
提前致谢
答案 0 :(得分:0)
我从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");
}