2011-10-31 101 views
1

首先,我會告訴你我做了什麼,並且有。我在ASP.NET MVC 3中的項目。ASP.NET MVC 3,SQL Server

這是表格Business的模型。

[Table("Business")] 
public class Business 
{ 
    [Key] 
    public long? BusinessId { get; set; } 

    public Int32 LegalTypeId { get; set; } 
    public Int16 BusinessTypeId { get; set; } 
    public Int64 OwnerId { get; set; } 
    public Int32 MainIndustryFieldId { get; set; } 
    public String NameNative { get; set; } 
    public String NameEnglish { get; set; } 
    public Byte[] Logo { get; set; } 
    public DateTime CreateDate { get; set; } 

    public virtual User Owner { get; set; }//It is Forign key with user table 
} 

[Table("User")] 
public class User 
{ 
    [Key] 
    public Int64 UserId { get; set; } 

    public String UserName { get; set; } 
    public String LoweredUserName { get; set; } 
    public String FirstName { get; set; } 
    public String LastName { get; set; } 
    public String Email { get; set; } 
    public String LoweredEmail { get; set; } 
    public String Password { get; set; } 
    public String PasswordSalt { get; set; } 
    public String PasswordQuestion { get; set; } 
    public String PasswordAnswer { get; set; } 
    public Boolean IsApproved { get; set; } 
    public Boolean IsLocked { get; set; } 
    public DateTime LastActivityDate { get; set; } 
    public DateTime LastLoginDate { get; set; } 
    public DateTime CreateDate { get; set; } 

    public virtual Business Bussines { get; set; } 
} 
時,我想補充信息

user.Business = new Business 
{ 
    OwnerId = user.UserId, 
    LegalTypeId = business.LegalTypeId, 
    BusinessTypeId = business.BusinessTypeId, 
    MainIndustryFieldId = business.MainIndustryFieldId, 
    NameNative = business.NameNative, 
    NameEnglish = business.NameEnglish, 
    Logo = business.Logo, 
    CreateDate = DateTime.Now 
}; 
ctx.SaveChanges(); 

我得到以下錯誤:

Cannot insert explicit value for identity column in table 'Business' when IDENTITY_INSERT is set to OFF.

在數據庫列標識規範業務選擇是Identity Yes

有人可以告訴做什麼。

回答

0

BusinessId不能爲空/ null,因爲您尚未指定它應該由Sql Server自動生成(其中Identity表示)。

由於您使用的代碼首先生成您的數據庫,只需更改爲:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
public long? BusinessId { get; set; } 
+0

我確實如你所說。現在給出以下錯誤: –

+0

ReferentialConstraint中的依賴屬性映射到商店生成的列。專欄:'BusinessId' –

+0

http://stackoverflow.com/questions/4035834/cant-insert-data-to-with-ef-with-master-detail-relationship – jgauffin

1

你能確保你的EDMX型號,BusinessId設置爲通過數據庫進行處理(財產StoreGeneratedPattern = Identity) ??另外:爲什麼是你的主鍵可空(long?) - 沒有任何意義。您的主關鍵字絕不能爲爲空!在的DbContext

enter image description here

0

覆蓋OnModelCreating及以下流利的API添加它:

modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);