c# - 在 Code First MVC 应用程序中查询 AspNet Identity 表

标签 c# asp.net-mvc entity-framework ef-code-first code-first

是否可以使用仿照 N 层设计基于关键字查询 AspNetUsers 表:

Implementing a generic data access layer using Entity Framework

我在 DAL 中创建了以下接口(interface):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library.Model;

namespace Library.DataAccessLayer
{
    ...

    public interface IAspNetUserRepository : IGenericDataRepository<ApplicationUser>
    {
    }

    public class AspNetUserRepository : GenericDataRepository<ApplicationUser>, IAspNetUserRepository
    {
    }
}

以及以下 BLL 条目:

using System;
using System.Collections.Generic;
using System.Linq;
using Library.DataAccessLayer;
using Library.Model;

namespace Library.BusinessLogicLayer
{
    public interface IBusinessLogicLayer_AspNetUser
    {
        ApplicationUser GetAspNetUserByAspNetUserID(string _UserID);
    }

    public class BusinessLogicLayer_AspNetUser : IBusinessLogicLayer_AspNetUser
    {
        private readonly IAspNetUserRepository _AspNetUserRepository;

        public BusinessLogicLayer_AspNetUser()
        {
            _AspNetUserRepository = new AspNetUserRepository();
        }

        public BusinessLogicLayer_AspNetUser(IAspNetUserRepository AspNetUserRepository)
        {
            _AspNetUserRepository = AspNetUserRepository;
        }

        public ApplicationUser GetAspNetUserByAspNetUserID(string _UserID)
        {
            return _AspNetUserRepository.GetSingle(u => u.Id.Equals(_UserID));
        }
    }
}

现在,在 BLL 文件中,唯一的 Lambda 表达式不包含 Td,因此会出错。

正确使用的型号是什么。我能找到的唯一信息是ApplicationUser继承了Identity User。

需要做什么或更改什么才能将这些字段添加到 ApplicationUser 模型而不影响数据库的 Code First 部分?

最佳答案

我终于找到答案了。它实际上就在盯着我的脸。

只需使用以下代码即可获取用户对象:

var context = new ApplicationDbContext();
var user = context.Users.{Methods and Lambda expressions};

例如,假设您需要现有KNOWN事件用户的用户名,请使用User.Identity.Name。并获取事件用户的 AspNetUsers 数据库记录:

var context = new ApplicationDbContext();
var user = context.Users.SingleOrDefault(u => u.UserName == User.Identity.Name);

关于c# - 在 Code First MVC 应用程序中查询 AspNet Identity 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434604/

相关文章:

c# - 调整图像大小以适合边界框

c# - 如何强制进行新的空 EF 迁移?

c# - 强制预先加载导航属性

c# - 使用简单的注入(inject)器注册 Web API Controller 的子集

c# - 在 Amazon Linux 上安装 mono 时出错

c# - 每次启动 ASP.NET Core MVC 应用程序时出现 IIS 错误

c# - WCF 服务或 Web API

ASP.NET MVC 站点在 AWS ELB 后面无法正常工作

entity-framework - Entity Framework 中的行版本比较

c# - Entity Framework 6 : Using interface as navigation properties possible?