c# - 对 ASP.NET 身份框架和 EF 代码优先的持久性无知

标签 c# entity-framework asp.net-identity poco

我用 POCO 类和我心中的持久无知原则开发了我的数据层。我的代码是这样的

POCO 类

 public class Report
{
    public int Id { get; set; }
    public string Name { get; set; }
   ...
    }
}

存储库接口(interface)

 public interface IReportRepository
{
    IEnumerable<Report> GetAllReports();
    Report GetReport(int reportId);
 ...
}

首先使用实体​​框架代码实现接口(interface),例如

 public class EFReportRepository : BaseRepository, IReportRepository
{
    public EFReportRepository(string connectionString)
        : base(connectionString)
    {
    }

    public IEnumerable<Report> GetAllReports()
    {
        return DbContext.Reports.Include(r => r.AggregationParameters).Include(r => r.ErrorAttachment).Include(r => r.ExcelAttachment).Include(r => r.XmlAttachment).ToList();
    }

    public Report GetReport(int reportId)
    {
        return DbContext.Reports.Include(r => r.AggregationParameters).Include(r => r.ErrorAttachment).
            Include(r => r.ExcelAttachment).Include(r => r.XmlAttachment).SingleOrDefault(r => r.Id == reportId);
    }

在添加授权(asp.net 身份)之前一切正常。

using Microsoft.AspNet.Identity.EntityFramework;

namespace DataRepository.Models
{
    public class MyUser : IdentityUser
    {
    }
}

现在每个报告都有创建该报告的用户

public class Report
{
    public int Id { get; set; }
    public string Name { get; set; }
   ...
    public MyUser CreatedByUser { get; set; }
    public string CreatedByUserId { get; set; }
   ...
   }
}

现在我对 Entity Framework 有紧密的依赖,我想省略它,因为从 IdentityUser 类继承。

如何排除这种依赖性?我将感谢任何帮助)

更新 现在的问题是创建 UserManager 对象。
UserManager 需要 IUserStore 作为输入参数。该接口(interface)在 Microsoft.AspNet.Identity.EntityFramework 命名空间中实现,称为 UserStore,所以我的代码是这样的

manager = new UserManager<MyUser>(new UserStore<MyUser>(MyDbContext)).

但是现在 MyUser 类不是从 IdentityUser 继承的,所以这段代码被破坏了(UserStore 需要这种类型的类)

最佳答案

我使用了这种方法,效果很好;

namespace DataRepository.Models
{
    public class MyUser
    {
        public int Id { get; }
        //define other user properties
    }       
}

namespace SomeOtherNamespace
{
    public class MyIdentityUser : IdentityUser
    {
        private MyUser _User;

        public MyIdentityUser(MyUser user)
        {
            _User = user;
        }

        public int Id { get { return _User.Id; } }
        //define other IdentityUser properties by using the MyUser object
    }
}

关于c# - 对 ASP.NET 身份框架和 EF 代码优先的持久性无知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30976487/

相关文章:

C#:如何使用 CategoryAttribute.Appearance 属性

c# - 如何使用 Entity Framework 6 自定义鉴别器列的名称、长度和值

asp.net - 如何手动获取 .aspnet.cookies Cookie 中的信息?

c# - MVC 应用程序过期应用程序 Cookie

c# - 将 View 中的整个对象绑定(bind)到 ViewModel 中的对象

c# - 以正确的顺序捕获进程 stdout 和 stderr

c# - 如何在winforms中禁用表格面板的水平滚动条

linq - 如何编写 Linq(或 lambda)语句来生成所有不在(或不存在)的元素

asp.net-mvc - 使用 Entity Framework 向 MVC 5 中的 Identity 添加属性

c# - 如何在 ASP.NET Core Identity 中检索用户的 2FA 恢复代码?