gpt4 book ai didi

c# - 将 ASP.NET 身份模型移动到类库

转载 作者:IT王子 更新时间:2023-10-29 03:57:26 24 4
gpt4 key购买 nike

我正在尝试使用此链接中的方法将身份模型移动到类库:

ASP.NET Identity in Services library

问题一:似乎一直在使用Website项目的连接字符串。我通过在类库中指定完整的连接字符串来克服它。我可以让 IdentityDbContext 使用类库的连接字符串吗?

问题2:由于问题1,如果我从网站项目中移除Entity Framework。在Website项目中寻找EF的SqlClient会报如下错误。

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

欢迎使用其他解决方案,只要它在网站项目中省略所有数据访问层引用,例如 EF。

最佳答案

要将 IdentityModel 移动到类库中(根据 SRP 是正确的做法),请执行以下步骤:

  1. 创建一个类库。 (类库1)
  2. 使用 NuGet,添加对 Microsoft.AspNet.Identity.EntityFramework 的引用。这也会自动添加一些其他引用。
  3. 在您的网站中添加对 ClassLibrary1 的引用
  4. 找到 WebSite/Models/IdentityModel.cs 并将其移动到 ClassLibrary1。
  5. 使 IdentityModel.cs 看起来像这样:

    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
    public ApplicationDbContext()
    : base("YourContextName")
    {
    }
    }
  6. 确保您网站的 Web.config 中的 YourContextName 指向该部分中的正确数据库。 (注意:该数据库可以而且应该存放您的应用程序数据)。

    <add name="YourContextName" connectionString="YourConnectionStringGoesHere"
    providerName="System.Data.SqlClient" />
  7. 让您的 EF Context 类继承自您的 ApplicationDbContext:

    public class YourContextName : ApplicationDbContext
    {
    public DbSet<ABizClass1> BizClass1 { get; set; }
    public DbSet<ABizClass2> BizClass2 { get; set; }
    // And so forth ...
    }

当您站点中的任何人尝试登录或注册时,Identity 系统会将他们路由到您的数据库以及所有您的数据,其中包括 Identity 表。

干得好!

关于c# - 将 ASP.NET 身份模型移动到类库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23446919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com