实体框架asp.net成员问题 [英] Entity framework asp.net membership problem

查看:108
本文介绍了实体框架asp.net成员问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在为学校创建一个网站,我正在使用实体框架代码firs作为数据访问。

i已经看到了激活asp.net会员的人们的视频实体框架中的角色提供者通过其API与它进行小的沟通,问题是我在visual studio上使用实体框架和asp.net mvc4互联网模板,当我想做更新时-datbase获取附加到visual studio的localdb上的成员资格表,它说:找不到存储过程''dbo.aspnet_CheckSchemaVersion''。

我不想通过aspnet_regsql.exe配置它,就像其他ppl一样只使用实体框架进行视频。

谢谢你...

Hi everyone,
im creating a website for school and im using entity framework code firs as Data Access.
i have seen videos where people where activating asp.net membership and role provider in entity framework by doing a small communication with it via its APIs,
problem is that im using entity framework and the asp.net mvc4 Internet template on visual studio and when im want to do update-datbase to get membership table on localdb attached to visual studio its says: "Could not find stored procedure ''dbo.aspnet_CheckSchemaVersion''."
and i dont want to configure it through aspnet_regsql.exe like other ppl where doing on video only using entity framework.
Thanks in advnce...

推荐答案

MVC4不使用与Asp.Net或Asp.NET MVC3使用的MemberShip相同的表和基础结构。你可以通过创建一个新的MVC4项目来看到它。您会注意到Model文件夹中有一个AccountModel.cs类。此外,在AccountController.cs中,您将看到来自WebMatrix命名空间的WebSecurity的使用。



默认配置不是问题,除非您要删除Model文件夹中的DbContext(不应该存在于DAL层内)。此外,在您想要在数据库中自动生成包含一些数据的表之前,这不是问题。使用WebSecurity创建用户非常容易,但是当您尝试使用它为数据库设定种子时则不是这样。实际上,您将收到错误消息,指出WebSecurity需要在使用前进行初始化,如果您初始化它,可能不会由Entity Framework创建数据库然后崩溃。



解决方案是使用程序包管理器控制台并使用一些命令行生成数据库。这个过程称为迁移。

删除默认代码



第一步是清理一些没有它的代码地点。要删除的第一个代码是在Models文件夹中的AccountModels.cs内。您将在文件顶部看到一个名为UsersContext的类。这需要删除。



需要删除的第二个代码是过滤器InitializeSimpleMembershipAttribute。如果未创建,此过滤器将为MemberShip创建表。由于我们不想动态创建,但是当应用程序启动时(或使用命令行),我们可以删除此过滤器。这是一个好主意,因为它使用我们刚刚删除的UsersContext。此文件位于Filters文件夹内。



要删除的第三个代码是AccountController.cs文件中AccountController类之上的过滤器使用。



当然,现在你必须设置你的DbContext才能做到UsersContext正在做的事情。如果您现在编译,它将无法编译,因为我们已删除UsersContext。但是,AccountController.cs中需要2行代码才能编译。第一个是在您的DbContext中创建一个方法来获取用户的名称,并创建一个新用户。下面是一个使用服务层来访问稍后将使用DbContext的存储库的示例。



配置实体框架迁移



下一步是确保web.config包含角色和成员资格的正确提供者。在web.config中,在system.web部分中确保您拥有以下代码。如果没有,请添加它。



MVC4 doesn’t use the same tables and infrastructure of MemberShip that Asp.Net or Asp.NET MVC3 used. You can see that just by creating a new MVC4 projet. You will notice that inside the Model folder that you have a class "AccountModel.cs". Also, inside the AccountController.cs you will see the use of WebSecurity that come from WebMatrix namespace.

The default configuration ain’t a problem until you want to remove the DbContext from the Model folder (which shouldn’t be there but inside the DAL layer). Also, it’s ain’t a problem until you you like to auto generate the table inside the database with some data into it. Creating a user is pretty easy with WebSecurity but it’s not when you try to seed the database with it. In fact, you will get error message saying that WebSecurity need to be initialized before use and if you initialize it, the database might not be created by Entity Framework and then it crashes.

The solution is to use the Package Manager Console and to generate the database with some commands line. This processes is called "Migration".
Removing default code

The first step is to clean up some code that doesn’t have its place. The first code to delete is inside AccountModels.cs inside the Models folder. You will see at the top of the file a class called UsersContext. This need to be removed.

The second code that need to be deleted is the filter InitializeSimpleMembershipAttribute. This filter create the tables for MemberShip if not created. Since we do not want to create on the fly but when the application start (or with commands line) we can delete this filter. It’s a good idea because it uses the UsersContext that we just deleted. This file is located inside the Filters folder.

The third code to remove is the filter use that is above the AccountController class inside AccountController.cs file.

Of course, now you have to setup your DbContext to be able to do what UsersContext was doing. If you compile now, it won’t compile because we have deleted the UsersContext. But, 2 lines of code is required inside AccountController.cs to be able to compile. The first one is to create in your DbContext a methbod to get the user by name and one to create a new user. Here is an example that use a "Service layer" to access the repository that will use a DbContext later.

Configure Entity Framework Migration

The next step is to make sure the the web.config contain the right provider for the role and membership. Inside web.config, in the system.web section be sure that you have the code below. If not, add it.

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
      <providers>
        <clear/>
        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
      </providers>
    </roleManager>
    <membership defaultProvider="SimpleMembershipProvider">
      <providers>
        <clear/>
        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
      </providers>
    </membership>







这将指明我们正在使用SimpleRoleProvider和SimpleMembershipProvider。说实话,我觉得MVC4是默认配置,所以你不需要这样做但是这个网站建议你这样做。



一旦完成,你需要构建迁移配置。如果您使用的是包管理器控制台,则会自动执行此操作。可以通过进入VIEW>其他Windows>包管理器控制台打开此工具。



下一步是使用下面的命令强制创建配置文件。这只需要一次。不要忘记使用EnableAutomaticMigration。这将允许您稍后根据您对模型和实体配置所做的更改来更新数据库。






This will specify that we are using the SimpleRoleProvider and the SimpleMembershipProvider. To be honest, I think with MVC4 it’s the default configuration so you do not required to do this but this website suggest to have it.

Once done, you need to build the Migration Configuration. This is automatically done if you are using the Package Manager Console. This tool can be open by going inside VIEW>Other Windows>Package Manager Console.

The next step is to use this command below that will force the creation of the configuration file. This will be required only once. Do not forget to use "EnableAutomaticMigration". This will let you update the database later accordingly to changes you made to your model and entity configuration.

Enable-Migrations –EnableAutomaticMigrations -Force





由于我们删除了UsersContext,因此我们在执行上述命令时不会发生任何冲突。否则,我们需要指定我们希望迁移发生的DbContext。此外,如果您已经有一个数据库初始化程序(IDatabaseInitializer),如DropCreateDatabaseIfModelChanges,这将不适用于DbMigrationsConfiguration。实际上,您需要删除任何初始化程序,因为我们正在切换到迁移配置。尽管如此,这将为我们提供额外的控制,更多的手动控制,但至少可以自动生成数据库,并使用成员资格和自定义表格对数据库进行播种。



命令使用Configuration.cs创建名为Migrations的文件夹。在Seed方法中,您将能够在数据库中创建所需的所有数据。这是一小段代码,可以创建一个角色,一个用户和一些实体。





Since we have removed the UsersContext we won’t have any conflict doing the command above. Otherwise, we would have need to specify which DbContext we want the migration to occur. Also, if you already had a database initializer (IDatabaseInitializer) like a "DropCreateDatabaseIfModelChanges", this won’t work with the DbMigrationsConfiguration. In fact, you need to remove any initializer because we are switching to the Migration configuration. Nevertheless, this will give us additionnal control, more manual control but at least the possibility to generate the database automatically and also seed the database with Membership and custom tables.

The command creates a folder called Migrations with a Configuration.cs. Inside the Seed method, you will be able to create all data you want inside the database. Here is a small snippet of code that create a role, a user and some entities.

internal sealed class Configuration : DbMigrationsConfiguration<WorkoutPlanner.Database.DatabaseContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(WorkoutPlanner.Database.DatabaseContext context)
    {
        base.Seed(context);

        WebSecurity.InitializeDatabaseConnection(
        "DefaultConnection",
        "UserProfile",
        "UserId",
        "UserName", autoCreateTables: true);

        if (!Roles.RoleExists("Administrator"))
            Roles.CreateRole("Administrator");

        if (!WebSecurity.UserExists("123123"))
            WebSecurity.CreateUserAndAccount("123123", "123123");

        if (!((IList<string>)Roles.GetRolesForUser("123123")).Contains("Administrator"))
            Roles.AddUsersToRoles(new[] { "123123" }, new[] { "Administrator" });

        context.Database.Initialize(true);
        context.Set<UserProfile>().Add(new UserProfile { UserId = 1, UserName = "123123" });

        context.Set<Workout>().Add(new Workout { Id = 1, Name = "My First workout user1", StartTime = DateTime.Now.Add(TimeSpan.FromDays(-10)), Goal = "Increase body mass" });
        context.Set<Workout>().Add(new Workout { Id = 2, Name = "My Second workout user1", StartTime = DateTime.Now, Goal = "Increase chest muscle, lower fat around abs" });


    }
}





最后一步是创建表模式和从种子配置中插入这些值。这是通过以下命令完成的:





The last step is to create table schema and insert those values from the seed configuration. This is done by this command :

update-database -verbose -force





详细信息将显示已执行的SQL语句,即使这些表中已存在数据,强制也会重新生成表。



结论



每次更改模型或实体配置时,都需要运行更新 - 数据库命令。这将删除表,再次创建它们,创建FK并插入种子数据。



The verbose will show you the SQL statement executed and the force will regenerate the table even if data already exist in those tables.

Conclusion

Any time you change your model or the configuration of your entities, you need to run update-database command. This will drop tables, create them again, create FK and insert seed data.


Jaydeep Jadav dude

当我创建一个新的mvc4项目时,他们没有被添加到我的web.config

无论如何,谢谢你提供了非常好的集成解决方案。
Jaydeep Jadav dude
when i create a new mvc4 project they are not added to my web.config
any way thank you offered very nice and integrated solution.


这篇关于实体框架asp.net成员问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆