0

我已經在這裏添加創建與實體框架代碼優先約束或鍵ApplicationUser

public class ApplicationUser : IdentityUser 
{ 
    public DateTime MembershipCreated { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public DateTime? Birthdate { get; set; } 
    public Gender Gender { get; set; } 
} 

與更多的數據ApplicationUser類我有另一個類「空間」,我想連接到ApplicationUser的ID,以便如果我嘗試刪除ApplicationUser條目並且存在與ApplicationUser條目相關聯的「空間」條目,則由於某個鍵或約束或其他原因會出現錯誤。

我該怎麼做才能做到這一點?

public class Space 
{ 
    public int SpaceId { get; set; } 

    [Index(IsUnique = false)] 
    [Required] 
    [MaxLength(128)] 
    public string AspNetUserRefId { get; set; } 

    //other members here 
} 

回答

0

你會somethink像這樣在你的空間類

[ForeignKey("ApplicationUser")] 
public int ApplicationUserID {get; set;} 
+0

你需要確保兩個類的名字是正確的是相同的,它和屬性在空間 – 2015-03-25 04:17:52

+0

我想這和更新數據庫時收到此錯誤信息。 「類型'project.DomainClasses.Models.MySpace.Space'屬性'ApplicationUserId'上的ForeignKeyAttribute無效。在依賴類型'project.DomainClasses.Models.MySpace.Space'中未找到導航屬性'ApplicationUser'。名稱值應該是有效的導航屬性名稱。「 – user1186050 2015-03-25 04:18:06

+0

請您進一步解釋一下嗎?我不明白你在說什麼。什麼樣的名字需要是「正確」的,什麼屬性應該在太空中? – user1186050 2015-03-25 04:19:26

0

這裏是我做的,但我現在有值分配給外鍵

我加的問題

[Required] 
public virtual ApplicationUser ApplicationUser { get; set; } 

給'空間'實體。 所以現在我看到一個名爲ApplicationUser_Id列,這是一個爲nvarchar(128)

但現在我有我的分配ID來這個領域的問題,當我創建一個新的「空間」實體,因爲我想分配字符串到應用程序用戶,這是一個類型的applicationuser而不是字符串。我想在字段中存儲字符串ID。

0

建立外鍵如下

public class ApplicationUser : IdentityUser 
{ 
    // other properties 

    public virtual ICollection<Space> Space { get;set;} 
} 

public class Space 
{ 
    // other properties 

    [ForeignKey("ApplicationUser")] 
    public string ApplicationUserId { get; set; } 
    public virtual ApplicationUser ApplicationUser { get; set; } 
}