我已将Migrations
从Web应用程序移植到类库项目。 一切工作正常,但我不能拨打static class Roles
。当前上下文中不存在名称'角色'
我已经包含了命名空间using System.Web.Security;
这哪里是Roles
所在。
这里是Configuration.cs文件内容:
namespace _DataContext.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using WebMatrix.WebData;
using System.Web.Security;
internal sealed class Configuration : DbMigrationsConfiguration<_DataContext.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(_DataContext.DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
SeedMembership();
}
private void SeedMembership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
// doesn't work either:
//var roles = (SimpleRoleProvider)Roles.Provider;
//var membership = (SimpleMembershipProvider)Membership.Provider;
if (Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
}
}
}
错误消息:
The name 'Roles' does not exist in the current context
缺少什么我在这里?
[编辑]
我一直在做一些调查研究,看来,我必须按顺序访问RoleExists
方法来创建从SimpleRoleProvider
的对象。
可是为什么我必须这样做,这条路?为什么我不能只使用:
if (Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
Roles
来自一个static class
?
嗨,就是这样!我没有引用System.Web!我很快将SimpleRoleProvider与角色进行了比较。似乎Roles提供了比SimpleRoleProvider更多的方法/属性。另外,为什么这是首选的方式?为什么不直接在if语句中检查角色是否存在? – Yustme 2013-05-09 16:22:39
正如我在我的回答中所提到的,SimpleRoleProvider是一个“自定义”角色提供者,它没有实现所有的方法,因为它们不是必需的。所以通过使用SimpleRoleProvider而不是Role,你实际上只会看到实现的方法。如果你从Role中调用一个未实现的方法,它只会抛出一个异常。此外,SimpleRoleProvider还提供了在角色中未找到的特定于使用SimpleMembership的其他方法。 – 2013-05-09 17:53:51
那我应该使用哪一个?简单的还是角色? – Yustme 2013-05-09 18:09:12