我无法创建DBContext实例

时间:2018-11-17 22:37:40

标签: asp.net asp.net-mvc entity-framework

我有模特:

public class Department
{
    public int DepartmentID { get; set; }
    [Required]
    [UniqueDepartmentName]
    public string Name { get; set; }
    public List<Person> Persons { get; set; }
}

和DBcontext:

public class InstituteContext : DbContext
{
    public InstituteContext (DbContextOptions<InstituteContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Department>().HasIndex(p => p.Name).IsUnique();
    }
    public DbSet<Institute.Models.Department> Department { get; set; }
}

如您所见,“ NAME”属性具有独特性。 为了进行验证,我创建了我的验证属性:

 public class UniqueDepartmentName : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var db = new InstituteContext();
    }
}

但是我不能创建InstituteContext的实例,因为构造函数需要参数。 我如何创建InstituteContext实例?还是应该在参数中传递给构造函数?

2 个答案:

答案 0 :(得分:0)

尝试一下:

public class UniqueDepartmentName : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var connectionString = "Your ConnectionString"
        var options = new DbContextOptionsBuilder<InstituteContext>()
                         .UseSqlServer(new SqlConnection(connectionString)).Options;

        using (var dbContext = new BloggingContext(options))
        {
           // Do necessary staffs here with dbContext
        }
    }
}

答案 1 :(得分:0)

您的DbContextOptions方法放置在错误的位置,您的构造函数可以为空,并且您需要添加方法OnConfiguring,该方法将接收DbContextOptions。 像这样:

public DbSet<Department> Department { get; private set; }

protected override void OnConfiguring(DbContextOptionsBuilder options) {
    // In my case I'm passing the connection string in this method below
    options.UseSqlServer("Data Source=DATABASEIP;Initial Catalog=DATABASETABLE;" +
        "User ID=USER;Password=PASSWORD");
}