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; } 
}