2016-10-26 94 views
1

我需要在.net核心库中的存储库类中包装一些函数。但我得到一个错误,我的构造函数没有正确的构造函数。我究竟做错了什么? 这里是我的DbContext代码从.net核心库获取存储库

public class effMercContext : DbContext 
{ 
    public DbSet<Department> Departments { get; set; } 
    public DbSet<Employee> Employees { get; set; } 
    public DbSet<Project> Projects { get; set; } 
    public effMercContext(DbContextOptions<effMercContext> options) 
     : base(options) 
    { 
    } 
} 
    public class EffMercDbContextFactory : IDbContextFactory<effMercContext> 
{ 
    public effMercContext Create(DbContextFactoryOptions options) 
    { 
     var builder = new DbContextOptionsBuilder<effMercContext>(); 
     builder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=pinchdb;Trusted_Connection=True;MultipleActiveResultSets=true"); 
     return new effMercContext(builder.Options); 
    } 
} 

我的仓库类到目前为止

public class EmployeeRepository 
{ 
    public Employee GetByID(int id) 
    { 
     using (effMercContext db = new effMercContext()) 
     { 

     } 
    } 
} 
+1

当然如果您定义了一个只能通过将特定参数传递给其构造函数来实例化的类,然后您尝试实例化该类而不传递任何参数给构造函数,那么它就不起作用。哪一部分不明显,你的类的构造函数需要一个参数,你是不是传递任何参数给你的构造函数,或者由此产生的错误?解释哪一部分不清楚可让答案专注于该部分。 – hvd

+0

我不清楚,如何实现我的存储库。我想制作这样的[链接](https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#using-framework-provided-services),但在.net核心库中,以及不是在界面中,但在类 –

+0

@ВасяПупкин但你的问题不处理这个话题。这是关于你的'DbContext'的一个错误。请提出一个新的问题属于这个主题 – rbr94

回答

0

您可以通过修改EmployeeRepository如下...

public class EmployeeRepository 
{ 
    var optionsBuilder = new DbContextOptionsBuilder<effMercContext>(); 
    // add necessary options 
    public Employee GetByID(int id) 
    { 
     using (effMercContext db = new effMercContext(optionsBuilder.Options)) 
     { 

     } 
    } 
} 

要了解更多信息,你可以按照this

1

那是因为你在这里调用构造函数不带参数:

public Employee GetByID(int id) { 
    using (effMercContext db = new effMercContext()) 
    { 

    } 
} 

但在你DbContext类,你只需要一个参数的构造函数:

public class effMercContext : DbContext { 
    public effMercContext(DbContextOptions<effMercContext> options) 
     : base(options) { 
    } 
} 

看看这篇文章,了解如何使用DbContextOptionshttps://docs.efproject.net/en/latest/miscellaneous/configuring-dbcontext.html

+0

好吧,所以我应该通过什么参数? –