Cannot insert the value NULL into column 'RoleId' (mvc4 simple membership)

前端 未结 2 669
花落未央
花落未央 2021-01-28 11:26

I noticed that someone else has faced the same problem such as Cannot insert the value NULL into column 'UserId' but it should be caused by different reasons.

Th

相关标签:
2条回答
  • 2021-01-28 12:13

    I think your problem is with the following section

    public partial class UsersInRole
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int RoleId { get; set; }
        public int UserId { get; set; }
    }
    

    Having the Key and DatabaseGeneratedAttribute is telling EF that the database is going to assign the value (IDENTITY column). However, your database is not auto assigning this value. So, when EF is trying to do the insert, it is ignoring your RoleId that you assigned because it thinks the database is going to auto assign it. Remove those two attributes on the RoleId property and see if you continue to have the same issues.

    0 讨论(0)
  • 2021-01-28 12:20

    1) Why are you using DbContext to add Roles to user? There are some native Membership methods to do it:

    Roles.AddUsersToRole(string[] usernames, string rolename)
    Roles.AddUserToRole(string username, string rolename) //**This one fits your purpose
    Roles.AddUserToRoles(string username, string[] rolenames)
    ...
    

    2) Value in key column can't be null

    3) Int can't be null in C#. If you want to set null value to int, you should define it as nullable: int?

    0 讨论(0)
提交回复
热议问题