C# 首先使用实体框架代码向ApplicationUser创建约束或键

C# 首先使用实体框架代码向ApplicationUser创建约束或键,c#,asp.net-mvc,entity-framework,data-annotations,asp.net-identity,C#,Asp.net Mvc,Entity Framework,Data Annotations,Asp.net Identity,我在这里添加了ApplicationUser类和更多数据 public class ApplicationUser : IdentityUser { public DateTime MembershipCreated { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime? Birthdate { get; se

我在这里添加了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; } 
}
我还有另一个类“Space”,我想连接到ApplicationUser的id,这样如果我尝试删除ApplicationUser条目,并且有一个与ApplicationUser条目关联的“Space”条目,我会因为键或约束或其他原因而出错

我该怎么做才能做到这一点

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

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

  //other members here
}

你在太空课上会有这样的想法

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

下面是我所做的,但是现在我在给外键赋值时遇到了问题

我补充说

[Required]
public virtual ApplicationUser ApplicationUser { get; set; }
到“空间”实体。 现在我看到一个名为ApplicationUser_Id的列,它是一个nvarchar(128)


但是现在,当我创建一个新的“Space”实体时,我在为这个字段分配id时遇到了一个问题,因为我试图为applicationuser分配一个字符串,它是applicationuser类型,而不是字符串。我想在字段中存储字符串id。

创建外键,如下所示

 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; }
}
公共类应用程序用户:IdentityUser
{
//其他属性
公共虚拟ICollection空间{get;set;}
}
公共类空间
{
//其他属性
[外键(“应用程序用户”)]
公共字符串applicationSerID{get;set;}
公共虚拟应用程序用户应用程序用户{get;set;}
}

您需要确保两个类名正确且相同,并且它和属性都在SPACE中。我尝试了此操作,在更新数据库时收到了此错误消息。“类型为”project.DomainClasses.Models.MySpace.Space“的属性'ApplicationUserId'上的ForeignKeyAttribute无效。在依赖类型'project.DomainClasses.Models.MySpace.Space'上找不到导航属性'ApplicationUser'。名称值应为有效的导航属性名称。请进一步解释?我不明白你在说什么。什么类名需要是“正确的”,什么属性应该在空间中?您是如何分配“ApplicationUser”的。这不是钥匙。。。是吗?他指的是一个班级/桌子