在Code First MVC应用程序中查询AspNet标识表

时间:2015-12-23 11:24:24

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

是否可以使用N-Tier设计基于关键字查询AspNetUsers表:

Implementing a generic data access layer using Entity Framework

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

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部分?

1 个答案:

答案 0 :(得分:3)

我终于找到了答案。实际上它正盯着我看。

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

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

例如,假设您需要现有的 KNOWN 活动用户的UserName,请使用User.Identity.Name。并获得活动用户的AspNetUsers数据库记录:

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