1

基本上我試圖在ASP.NET中已經建立的SimpleMembership擴大MVC 4 我想補充一點,有我用下面的代碼和插入試圖0如何在Code First中爲屬性設置默認值?

初始值的平衡場沒有在餘額字段:

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    public string RealName { get; set; } 
    public int Balance { get; set; } 
} 

但不幸的是,我得到一個異常時,我嘗試創建一個新用戶(無餘額),我不能平衡插入空,因爲它不允許空值。 如何在Code First中將餘額設置爲0作爲默認值。

回答

0

int Balance 

不允許爲空,但

int? Balance 

一樣。

如果要控制數據庫級別的結構,請使用顯式遷移並手動調整生成的遷移代碼,以便在數據庫級別設置默認值。如果您想在代碼級別使用默認值,只需在該類的默認構造函數中設置該值即可。

+0

感謝很多 - 但說我想要的值是0,而不是空。 我已經嘗試不工作的情況如下: [表( 「用戶配置」)] 公共類用戶配置 { 公共用戶配置() { 餘額= 0; } [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId {get;組; } public string UserName {get;組; } public string RealName {get;組; } public int?平衡{get;組; } } –

+0

在構造函數中設置默認值。 –

+0

那麼我做了: public UserProfile(){Balance = 0; } 但它不會將其設置爲0 –

0

第一條:您可以使用這樣的構造:

[Table("UserProfile")] 
public class UserProfile 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int UserId { get; set; } 
    public string UserName { get; set; } 
    public string RealName { get; set; } 
    public int Balance { get; set; } 

    public UserProfile() 
    { 
    this.Balance = 0; 
    } 
} 

其次,清潔和重建方案,然後使用遷移命令

Update-database -verbose 
相關問題