如何从Controller外部访问DbContext?

时间:2015-12-14 14:16:53

标签: asp.net entity-framework

我有类UserFactory,我想检查用户是否已存在于数据库中,否则将自动创建。但是从Controller外部访问DbContext有困难。

    public UserFactory(DbContextOptionsBuilder builder)
    {
        _dbContext = new PMSContext(builder.Options) ;
    }

    public User Create(WindowsIdentity currentWindowsUser)
    {
        User user = new User();
        string name = currentWindowsUser.Name.Replace("DOMAIN\\", "");

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal ADuser = UserPrincipal.FindByIdentity(ctx, name);

        if(ADuser != null)
        {
            User userInDatabase = _dbContext.Users.Where(u => u.SamAccountName == name).FirstOrDefault();
        }
   }

而且比起Startup.cs我还是:

    public Startup(IHostingEnvironment env)
    {
        var builder = new DbContextOptionsBuilder<PMSContext>()
        .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
        User user = new UserFactory(builder).Create(WindowsIdentity.GetCurrent());
    }

但我收到错误:

  

严重级代码说明项目文件行   错误CS1503参数1:无法转换为&#39; Microsoft.Data.Entity.Infrastructure.SqlServerDbContextOptionsBuilder&#39; to&#39; Microsoft.Data.Entity.DbContextOptionsBuilder&#39;

这是从Controller外部访问DbContext的正确方法吗?

1 个答案:

答案 0 :(得分:0)

答案很简单:

var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
var context = new PMSContext(optionsBuilder.Options);

User user = new UserFactory(context).Create(WindowsIdentity.GetCurrent());