2015-05-14 77 views
0

目前我正在试图给帐户模型类中添加一个额外的模型,像这样加公司的模式,以账户类

public class RegisterViewModel 
{ 
    [Required] 
    [EmailAddress] 
    [Display(Name = "Email")] 
    public string Email { get; set; } 

    [Required] 
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
    [DataType(DataType.Password)] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 

    [DataType(DataType.Password)] 
    [Display(Name = "Confirm password")] 
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
    public string ConfirmPassword { get; set; } 

    public int companyID { get; set; } 

    public virtual CompanyDetails company { get; set; } 
} 

public class CompanyDetails 
{ 
    [Key] 
    public int companyID { get; set; } 

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 1)] 
    [Display(Name = "Company Name")] 
    public string CompanyName { get; set; } 
} 

我什么不知道的是如何创建一个DBSet有公司类,并会公司的ID栏出现在用户表中?

+0

您有一个名为View Model的类型,但想要一个'DbSet ':我想你可能会混淆Model和View Model。你是在EF还是在客户端寻找这个? – Richard

+0

@Richard我在EF寻找这个。我创建项目时自动生成了RegisterViewModel。 – Johnathon64

+0

再次想到我不认为这是EF。我试图实现的基本上是在用户表中有一个外键,它将连接到公司表 – Johnathon64

回答

1

MVC 5利用身份,其中除了别的以外,还带有默认的ApplicationUser类。这是您的应用程序的“用户”,以及Entity Framework为您的数据库所坚持的内容。因此,您需要在此处添加其他关系,而不是RegisterViewModel,正如名称所示,它是视图模型,而不是实体。

IdentityModels.cs

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 

    public virtual CompanyDetails Company { get; set; } 
} 

一旦你产生迁移和更新数据库,你dbo.CompanyDetails表将被创建和外键,该表将被添加到dbo.AspNetUsers(表为ApplicationUser

您当然需要保留RegisterViewModel的属性,以便实际编辑那些使用该视图模型的字段,但是您可以删除virtual关键字。 virtual关键字表示可以重写属性或方法,这对于实体的导航属性是必需的,以便实体框架可以将延迟加载逻辑附加到它创建的代理类上。这可能比你需要更多的信息,但是总而言之,在你的视图模型中并不需要。

+0

我做了一些更多的挖掘,并意识到我的公司详细实体应该放在IdentityModels,CS中。我是否也应该将公司详细信息类移入IdentityModels.cs文件中?我还发现IdentityDBContext不确定我是否也应该使用它,以实现我想要的功能。 – Johnathon64

+0

不,我不确定为什么MVC开发人员选择以这种方式设置项目模板。传统上,每个类都有自己的文件。所以'CompanyDetails'会放在'CompanyDetails.cs'中。你不用*这样做,显然,它使得维护你的应用变得更容易,因为你不必考虑一个类是什么文件。 –

相关问题