如何将会员资格提供商与 EF Code First 结合使用?

发布于 2024-10-14 03:59:01 字数 106 浏览 1 评论 0原文

我有基于 EF Code First 的模型,我想将它们与默认的 MembershipProvider 一起使用,但我不知道如何正确编写模型,因此在进行更改时它不会删除重新创建表时的所有数据到模型。

I have models based on EF Code First and I want to use them with the default MembershipProvider, but I don't know how to write the model correctly, so it won't erase all my data on recreating the tables when there were changes made to the model.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

不再让梦枯萎 2024-10-21 03:59:02

你的问题有两个部分。

  1. 如何首先通过 EF 代码使用 ASP.NET 会员 API?
  2. 当模型发生变化时如何保留现有数据?

至于模型更改时如何保留现有数据,就 EF 4.0/asp.net mvc 3 而言,尚不支持数据库迁移。您将必须迁移到支持数据库迁移的 asp.net mvc 4.0/ EF 4.3 或使用类似的替代方案,但其仍为测试版。

asp scott gu 博客中的 .net mvc 4.0 数据库迁移

现在首先介绍如何通过 EF 代码使用 ASP.NET 会员提供程序。有几个挑战:

  1. 我们不能/不应该与 ASP.NET 成员资格提供程序表进行联接。不建议这样做,所以我的建议是为 ASP.NET 成员资格提供程序类创建一个“适配器类”。例如:

     公共类 UserAdapter
     {
     // 所有与用户相关的属性。不存储在成员模式中,而是存储在您的模式中
    
       公共字符串用户代理名称;
    
       // 存储在成员模式中的一些属性
       [未映射]
       公共字符串电子邮件{ 
            得到
            {
                  Membership.GetUser(UserProxyName).Email; 
            }                
       }        
    
      // 一些属性存储在成员模式中而不是您的模式中
      [未映射]
      公共字符串[]用户角色
      {
        得到
        {
            返回 Roles.GetRolesForUser(UserProxyName);
        }           
      }
    
    }
    

    现在为了更新信息,您可以在模型本身中编写一些函数,但是我建议创建一个具有存储库设计模式的UserRepository来处理用户CRUD操作。

  2. 第二个挑战是如何在第一次运行时创建数据库。由于播种成为一个问题,如果您想要播种用户信息,那么单独运行 aspnet_regsql 效率不高,因为在播种发生之前需要成员架构。我发现了这篇不错的文章,经过一些微调,它对我很有用:

asp.net 会员资格和 EF

Your question has two parts.

  1. How to use asp.net membership API with EF code first?
  2. How to preserve existing data when model changes?

as for How to preserve existing data when model changes, as far as with EF 4.0/ asp.net mvc 3, database migrations are not yet supported. You will have to move to asp.net mvc 4.0/ EF 4.3 where database migrations are supported or use similar alternatives , but its still beta release.

asp.net mvc 4.0 database migration in scott gu's blog

Now coming to the point on how to use asp.net membership provider with EF code first. There are couple of challenges :

  1. We cannot/should not do an join with asp.net membership provider tables. Its not recommended, so my suggestion will be to create a "adapter class" for asp.net membership provider classes. For ex :

     public class UserAdapter
     {
     // all user related attributes. Not stored in membership schema, but your schema
    
       public string UserProxyName;
    
       // some attributes stored in membership schema
       [NotMapped]
       public string Email { 
            get
            {
                  Membership.GetUser(UserProxyName).Email; 
            }                
       }        
    
      // some attributes stored in membership schema and not in your schema
      [NotMapped]
      public string[] UserRoles
      {
        get
        {
            return Roles.GetRolesForUser(UserProxyName);
        }           
      }
    
    }
    

    Now for updating information , you may write some functions in Model itself, however i would suggest create a UserRepository with repository design pattern to handle user CRUD operations.

  2. Second challenge is how to create the database on first run. As seeding becomes an issue, if you want to seed user information then seperately running aspnet_regsql is not efficient as membership schema is expected before the seeding happens. I came across this nice article , with some fine tuning it worked for me :

asp.net membership and EF

情徒 2024-10-21 03:59:02

目前 (EF 4.1 CTP) EF Code First 没有该选项。如果您对模型进行了更改,它总是会删除一个表。

更新

EF 4.1 RTM 允许您创建自定义数据库初始值设定项并指定数据库对象的创建和数据播种。

Currently (EF 4.1 CTP) EF Code First doesn't have that option. It always drops a table if you made changes to model.

Update:

EF 4.1 RTM allows you to create a custom database initializer and specify creation of db objects and data seeding.

回忆那么伤 2024-10-21 03:59:02

如果您使用的是 SQL Server,请检查以下内容:

http://www.paragm.com/ef-v4-1-code-first-and-asp-net-membership-service/

御守 2024-10-21 03:59:02

还有我的库,它基本上允许您定义几乎所有内容的配置方式,包括:键类型、上下文对象所在的位置以及用户/角色实体所在的位置。可使用抽象基类或接口进行扩展。与存储库模式/工作单元/IoC 容器一起开箱即用也很好。

来源: https://github.com/holyprin/holyprin.web.security

NuGet: https://nuget.org/packages/Holyprin.Web.Security

There is also my library which basically allows you to define how almost everything should be configured including: key type, where the your context object is, and where your user/role entities are located. Extendable using abstract base classes or interfaces. Also works quite well out of the box with repository pattern / unit of work / IoC Containers.

Source: https://github.com/holyprin/holyprin.web.security

NuGet: https://nuget.org/packages/Holyprin.Web.Security

恍梦境° 2024-10-21 03:59:02

在我的 DbContext.cs 文件中,我有一个 Seed 函数,我可以在其中调用 ApplicationServices.InstallServices() 将 ASP.NET 成员资格安装到我的数据库中。现在,每当我的初始化程序删除数据库时,它都会再次重新创建 ASP.NET 成员资格架构。

public class PanelInitializer : DropCreateDatabaseAlways<PanelContext>
{
    protected override void Seed(PanelContext context)
    {
        //Install ASP.NET Membership
        ApplicationServices.InstallServices(SqlFeatures.Membership | SqlFeatures.RoleManager); 

        new List<Panel>
            {

ApplicationServices 类

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Management;

namespace Lansw.Panels.DataAccess.Contexts
{
    public class ApplicationServices
    {
        readonly static string DefaultConnectionString = ConfigurationManager.AppSettings["DefaultConnectionString"];
        readonly static string ConnectionString = ConfigurationManager.ConnectionStrings[DefaultConnectionString].ConnectionString;
        readonly static SqlConnectionStringBuilder MyBuilder = new SqlConnectionStringBuilder(ConnectionString);

        public static void InstallServices(SqlFeatures sqlFeatures)
        {
            SqlServices.Install(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
        }

        public static void UninstallServices(SqlFeatures sqlFeatures)
        {
            SqlServices.Uninstall(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
        }
    }
}

感谢 @ImarSpaanjaars http://imar.spaanjaars.com/563/using-entity-framework-code-first-and-aspnet-membership -在一起

In my DbContext.cs file I have a Seed function where I call the ApplicationServices.InstallServices() to install the ASP.NET Membership to my database. Now everytime my initializer drop the database it recreates ASP.NET Membership schema again.

public class PanelInitializer : DropCreateDatabaseAlways<PanelContext>
{
    protected override void Seed(PanelContext context)
    {
        //Install ASP.NET Membership
        ApplicationServices.InstallServices(SqlFeatures.Membership | SqlFeatures.RoleManager); 

        new List<Panel>
            {

The ApplicationServices class

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Management;

namespace Lansw.Panels.DataAccess.Contexts
{
    public class ApplicationServices
    {
        readonly static string DefaultConnectionString = ConfigurationManager.AppSettings["DefaultConnectionString"];
        readonly static string ConnectionString = ConfigurationManager.ConnectionStrings[DefaultConnectionString].ConnectionString;
        readonly static SqlConnectionStringBuilder MyBuilder = new SqlConnectionStringBuilder(ConnectionString);

        public static void InstallServices(SqlFeatures sqlFeatures)
        {
            SqlServices.Install(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
        }

        public static void UninstallServices(SqlFeatures sqlFeatures)
        {
            SqlServices.Uninstall(MyBuilder.InitialCatalog, sqlFeatures, ConnectionString);
        }
    }
}

Thanks to @ImarSpaanjaars http://imar.spaanjaars.com/563/using-entity-framework-code-first-and-aspnet-membership-together.

挽梦忆笙歌 2024-10-21 03:59:01

看看这个项目

http://codefirstmembership.codeplex.com/

它有用户和角色的实体类,以及角色提供者和成员提供者实现。如果您在数据上下文类中包含用户和角色,则将在数据库中创建表。

Have a look at this project

http://codefirstmembership.codeplex.com/

It has entity classes for users and roles, as well as a roleprovider and membershipprovider implementation. If you include the users and roles in your datacontext class the tables will be created in your database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文