webpages_UsersInRoles代码第一个FK错误

本文关键字:FK 错误 第一个 代码 UsersInRoles webpages | 更新日期: 2023-09-27 18:11:00

我正在尝试实现simplemember实体,以便我可以控制它的某些方面,以下是我创建的类:

 [Table("webpages_Roles")]
 public class Role
{
    public Role()
    {
        UsersInRoles = new List<UsersInRole>();
    }
    [Key]
    public int RoleId { get; set; }
    [StringLength(256)]
    public string RoleName { get; set; }
    //public ICollection<Membership> Members { get; set; }
    [ForeignKey("RoleId")]
    public ICollection<UsersInRole> UsersInRoles { get; set; }
}
[Table("webpages_UsersInRoles")]
public class UsersInRole
{
    [Key, Column(Order = 0)]
    public int RoleId { get; set; }
    [Key, Column(Order = 1)]
    public int UserId { get; set; }
    [Column("RoleId"), InverseProperty("UsersInRoles")]
    public Role Roles { get; set; }
    [Column("UserId"), InverseProperty("UsersInRoles")]
    public Membership Members { get; set; }

}
 [Table("webpages_Membership")]
public class Membership
{
    public Membership()
    {
        //Roles = new List<Role>();
        OAuthMemberships = new List<OAuthMembership>();
        UsersInRoles = new List<UsersInRole>();
    }
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId { get; set; }
    public DateTime? CreateDate { get; set; }
    [StringLength(128)]
    public string ConfirmationToken { get; set; }
    public bool? IsConfirmed { get; set; }
    public DateTime? LastPasswordFailureDate { get; set; }
    public int PasswordFailuresSinceLastSuccess { get; set; }
    [Required, StringLength(128)]
    public string Password { get; set; }
    public DateTime? PasswordChangedDate { get; set; }
    [Required, StringLength(128)]
    public string PasswordSalt { get; set; }
    [StringLength(128)]
    public string PasswordVerificationToken { get; set; }
    public DateTime? PasswordVerificationTokenExpirationDate { get; set; }
    //public ICollection<Role> Roles { get; set; }
    [ForeignKey("UserId")]
    public ICollection<OAuthMembership> OAuthMemberships { get; set; }
    [ForeignKey("UserId")]
    public ICollection<UsersInRole> UsersInRoles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public bool Status { get; set; }
    public string EmailId { get; set; }
}

现在,只要我尝试插入一个新用户,它就会正确地插入到表userProfile和webpages_Membership上,但只要应用程序试图为用户分配一个角色,就会抛出异常

* INSERT语句与外键约束FK_dbo.webpages_UsersInRoles_dbo.webpages_Membership_UserId冲突。冲突发生在数据库"PCSPI",表"dbo"。webpages_Membership",列"UserId"。语句已终止。*

我试图用sql server手动插入它,它插入,但一旦我试图在我的应用程序上做它,异常被抛出。

我做错了什么?这个模型不是很明确吗?提前感谢

webpages_UsersInRoles代码第一个FK错误

您没有阅读评论。我想你是从:http://blog.spontaneouspublicity.com/including-asp-net-simple-membership-tables-as-part-of-your-entity-framework-model

下面的一个评论说模式是不正确的,并给出了正确的模式,defo工作,因为我正在使用它。我不想在这里重复。去上面提到的网站再检查一下。(Senad Karic评论)

注:别担心,我第一次用的时候也是这么做的:)