2015-05-14 74 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'中。你不用*這樣做,顯然,它使得維護你的應用變得更容易,因爲你不必考慮一個類是什麼文件。 –

相關問題