【问题标题】:Intranet Application - Data Access in separate projectIntranet 应用程序 - 单独项目中的数据访问
【发布时间】:2014-01-07 15:22:28
【问题描述】:

我有一个使用 EF 6 的 MVC Intranet 应用程序。我已经在一个单独的类库中设置了 DataAccess 项目,该类库引用了 EF 6。我有一个实现接口的实体:

public interface IAuditable
{
    DateTime CreatedDateTime { get; set; }
    string CreatedBy { get; set; }
}

public class Collection : IAuditable
{
    // Properties
}

但是,在 SaveChanges 方法中,我显然无法访问 HttpContext.Current.User.Identity.Name,因为它位于单独的类库中,所以我想知道如何在 SaveChanges 中设置它?

public override int SaveChanges()
{
    var addedEntries = ChangeTracker.Entries().Where(x => x.State == EntityState.Added);

    foreach (var dbEntityEntry in addedEntries)
    {
        var entity = dbEntityEntry.Entity as IAuditable;

        if (entity != null)
        {
            entity.CreatedDateTime = DateTime.Now;
            // how do I set entity.CreatedBy = HttpContext.Current.User.Identity.Name?
        }
    }

    return base.SaveChanges();
}

编辑

继@CodeCaster 解决方案之后,我有以下内容:

[BreezeController]
public class BreezeController : ApiController
{
    private readonly BTNIntranetRepository _repository; 

    public BreezeController(BTNIntranetRepository repository)
    {
        _repository = repository;
        _repository.LoggedInUser = HttpContext.Current.User.Identity.Name;
    }

    // Methods
}

HttpContext.Current.User 为空

【问题讨论】:

  • 您的HttpContext.Current.User 为空是一个完全不同的问题,这可能与您设置身份验证和 IoC 容器的方式有关。它在动作方法中设置了什么?一个技巧是每次在使用它之前在存储库上设置它,但在这种情况下你可能会做entity.CreatedBy=...
  • 我已经启用了 Windows 身份验证,如果我没有在构造函数中设置它(例如在 ApiController 上的方法之一),我可以看到 Identity.Name 的值,但如果我这样做了, 那么User 为空

标签: asp.net-mvc entity-framework


【解决方案1】:

这可以通过多种方式解决。

您并没有真正显示相关代码,但是您可以为库类提供一个公开的 string LoggedInUser(或 ActingUser 或给它一个名称)属性,该属性是您在实例化它时设置的:

public class SomeController : Controller
{
    private IDataSource _dataSource;

    public SomeController(IDataSource dataSource)
    {
        _dataSource = dataSource;
        _dataSource.LoggedInUser = HttpContext.Current.User.Identity.Name
    }
}

然后您可以在 IDataSource.SaveChanges() 方法中简单地使用该属性:

public override int SaveChanges()
{
    // ...

    entity.CreatedBy = this.LoggedInUser;
}

【讨论】:

  • 控制器是一个ApiController。在构造函数中设置它的问题是当我在 IoC 中实例化控制器时未设置 HttpContext.Current.User
  • 我已经编辑了我的问题,希望能显示更多相关代码?
  • 我所做的是在我的 repo 上调用 SaveChanges 之前,我调用了一个方法来设置我的 repo 上的当前用户,这反过来又在上下文中设置了 LoggedInUser 的值和解决了问题!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 2018-03-22
相关资源
最近更新 更多