具有部分 DbContext MVC 5 的身份 2.0 用户

Identity 2.0 User with partial DbContext MVC 5

我想在我的上下文中部分 class 添加一些 "automated" 功能,例如 CreatedByModifiedBy

我有两个项目: DataAccess 和 MVC(启动项目)。

我无法在我的上下文部分 class 文件夹 Context 中获取程序集引用(请看照片),有什么办法可以做到这一点吗?我已经安装了所有必要的 nu-get 组件

所以,当我尝试调用 User.Identity.GetUserId(); 时,我有红色下划线 正如您在图片上看到的,我什至在该项目 (DataAccess) 中提取了 class IdentityModels.cs,但没有成功。

我的上下文 class 看起来像:

 using System;
 using System.Collections.Generic;
 using System.Data.Entity;
 using System.Data.Entity.Core.Objects;
 using System.Data.Entity.Infrastructure;
 using System.Data.SqlClient;
 using System.Linq;
 using System.Net;
 using System.Text;
 using System.Threading.Tasks;
 using System.Web; 
 using System.Web.Mvc;
 using Microsoft.AspNet.Identity;
 using Microsoft.VisualBasic.ApplicationServices;
 using Owin;

 namespace DataAccess
{
public partial class SalesManagementEntities
{

    private bool doSaveChangesOverride = true;

    public bool DoSaveChangesOverride
    {
        set { doSaveChangesOverride = value; }
        get { return doSaveChangesOverride; }
    }

    public override int SaveChanges()
    {
        try
        {
            if (DoSaveChangesOverride)
                SaveChangesOverride();
            return base.SaveChanges();
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }

    public override Task<int> SaveChangesAsync()
    {
        if (DoSaveChangesOverride)
            SaveChangesOverride();

        return base.SaveChangesAsync();
    }

    private void SaveChangesOverride()
    {
        ObjectContext context = ((IObjectContextAdapter)this).ObjectContext;

        //Find all Entities that are Added/Modified that inherit from my EntityBase
        IEnumerable<ObjectStateEntry> objectStateEntries =
            from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
            where
                e.IsRelationship == false &&
                e.Entity is IEntityBase
            select e;

        var currentTime = DateTime.Now;

        string userId = User.Identity.GetUserId();

        foreach (var entry in objectStateEntries)
        {
            var entityBase = entry.Entity as IEntityBase;

            if (entry.State == EntityState.Added)
            {
                entityBase.SetCreatedDateTime(currentTime);
                entityBase.SetCreatedBy(userId);

            }

            entityBase.SetModifiedDateTime(currentTime);
            entityBase.SetModifiedBy(userId);
        }
    }

}
}

以下代码:

User.Identity.GetUserId();

仅当您在 mvc 控制器内时才有效,因为 mvc 控制器公开了一个名为 User 的 属性,它属于 IPrincipal 类型,让您可以访问 IPrincipal 成员喜欢 Identity 等...

你的 DbContext 没有 User 属性 而是 User class 并且编译器会尝试检查静态 属性 命名为 Identity 存在于那个 class 中并且不会找到 属性 并最终为此引发错误。

要在您的 DAL 层中获取当前用户 ID,您必须使用以下代码:

// There is no nuget package to install to get the user name.
// If the user name is unique into your database table then 
// you can request your DbContext and get the user id.
var userName = System.Web.HttpContext.Current.User.Identity.Name;

如果您想像使用 GetUserIdGetUserId<T> 扩展方法获取控制器中的用户 ID,请使用以下代码:

// You need to install the Microsoft.AspNet.Identity.Core nuget package
// and get the user id like this:
var userId = System.Web.HttpContext.Current.User.Identity.GetUserId();

我建议您使用可以为您提供当前 IIdentity 的服务。这样做将有助于单元测试,因为模拟当前用户很容易。