在控制器asp.net mvc中使用多个数据库

时间:2015-09-17 13:45:39

标签: c# asp.net-mvc

我有两个独立的VS解决方案,可以很好地访问与它们相关的数据库。

我怎么需要从另一个数据库中查找一些细节,以便在另一个解决方案中显示。

我已将第二个连接字符串添加到web.config,然后将上下文添加到我的DAL:

namespace RACentral.DAL
{
public class RACentralContext : DbContext
{

    public RACentralContext()
        : base("RACDev")
    {
    }

    public DbSet<RiskAssessment> RiskAssessments { get; set; }
    public DbSet<Hazard> Hazards { get; set; }
    public DbSet<PPE> PPEs { get; set; }
    public DbSet<RiskAssessmentPPE> RiskAssessmentPPEs { get; set; }
    public DbSet<PeopleExposed> PeopleExposeds { get; set; }
    public DbSet<RiskAssessmentPeopleExposed> RiskAssessmentPeopleExposeds { get; set; }
    public DbSet<RiskAssessmentHazard> RiskAssessmentHazards { get; set; }
    public DbSet<ControlMeasure> ControlMeasures { get; set; }
    public DbSet<Severity> Severitys { get; set; }
    public DbSet<Likelihood> Likelihoods { get; set; }
    public DbSet<AddControlMeasure> AddControlMeasures { get; set; }
    public DbSet<Type> Types { get; set; }
    public DbSet<SubType> SubTypes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

public class PeopleContext : DbContext
{

    public PeopleContext()
        : base("PeopleContext")
    {

    }

    public DbSet<Person> People { get; set; }
}
}

我在控制器中出错

  

&#39;未设置为对象的实例,&#39;

我试图在我的控制器中访问它,如下所示:

public class RiskAssessmentController : Controller
{
    private RACentralContext db = new RACentralContext();
    private PeopleContext Peopledb = new PeopleContext();

    public ViewResult StartRA()
    {
        var user = User.Identity.Name;
        string userName = user.Substring(7);
        var test = Peopled.Person.FirstOrDefault(x => x.PersonId == 1) //Error here


        StartRiskAssessmentViewModel viewModel = new StartRiskAssessmentViewModel
        {
            RiskAssessment = new RiskAssessment(),
            Assessor = userName,

        };

        return View(viewModel);
    }
}

0 个答案:

没有答案