作为参考,我已经按照这个公认的答案的建议来解决问题。
具体来说,当我尝试添加新角色时,我的aspnet_Roles
表出现问题。请参阅下面的我的模型和代码:
public partial class aspnet_Roles
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
public aspnet_Roles()
{
RoleId = Guid.NewGuid();
aspnet_Users = new HashSet<aspnet_Users>();
}
public Guid ApplicationId { get; set; }
[Key]
public Guid RoleId { get; set; }
[Required]
[StringLength(256)]
public string RoleName { get; set; }
[Required]
[StringLength(256)]
public string LoweredRoleName { get; set; }
[StringLength(256)]
public string Description { get; set; }
public virtual aspnet_Applications aspnet_Applications { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<aspnet_Users> aspnet_Users { get; set; }
}
该模型非常标准...我将NewGuid
赋值添加到构造函数中,因为我首先构建此代码。我不确定 ASP 成员资格是否适用于int
值,所以我(不情愿地)坚持 Guids。
我正在使用Web.Security.Roles
包装器通过CreateRole
添加角色:
protected override void Seed(Ortund.Models.OrtundDbContext context)
{
Roles.CreateRole("global"); // Supreme ruler of all that he surveys.
Roles.CreateRole("admin"); // Has some privileges.
Roles.CreateRole("user"); // Nothing special happening here.
}
据我了解,鉴于添加了RoleId = Guid.NewGuid()
赋值的模型,我现在应该能够将这些角色添加到数据库中而不会出错,因为这显然是为了模拟newid()
赋值作为数据库上的默认值。
然而,事实并非如此。
有趣的是,如果我确实在数据模型之外更新数据库以包含newid()
或newsequentialid()
默认值,则可以使用上述代码毫无困难地添加角色。
如果我不添加数据库上的默认值,Visual Studio 调试器中会出现以下错误:
无法将值 NULL 插入到表 'RoleId' 列 'OrtundStuff.dbo.aspnet_Roles' 中;列不允许空值。插入失败。
我错过了什么?为什么这个NewGuid()的东西不起作用?
您的模型看起来不错,但您正在使用System.Web.Security.Roles
来管理角色。没关系,但不要指望框架会在不告诉它这样做的情况下使用你的模型。
恐怕你应该基于抽象类System.Web.Security.RoleProvider编写自己的角色提供程序。在其实现中使用 EF 的上下文和模型。
然后将提供程序的实例设置为 Security.RoleProvider,以便对象Roles
的每个方法都将使用您的实现。