简体   繁体   中英

Exception on creating a table from C# Entity framework MVC

public class SalesERPDAL:DbContext
{
    public DbSet<Employee> Employees;
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().ToTable("TblEmployee");
        base.OnModelCreating(modelBuilder);
    }
}

public class EmployeeBusinessLayer
{
    public List<Employee> GetEmployees()
    {
        SalesERPDAL salesDalObj = new SalesERPDAL();
        return salesDalObj.Employees.ToList(); **//Getting error on this call**
    }
}


public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public int Salary { get; set; }
}

webconfig connection string:

<connectionStrings>
<add name="SalesERPDAL" connectionString="Data Source=CSCINDAI406933\\SQLEXPRESS;Initial Catalog=SalesERPDB;Integrated Security=True;"></add>

Trying to create a table "TblEmployee" from "SalesERPDAL" class, as mentioned above. But I'm getting a runtime error on calling "salesDalObj.Employees.ToList();" from GetEmployees() from EmployeeBusinessLayer class.

Exception details: Argument Null exception was unhandled by user code: An exception of type 'System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code Additional information: Value cannot be null.

I'm able to connect to this DataBase from a different application. I'm new to Entity framework, not sure why the application is breaking. Help would really be appreciated. Thanks in advance.

You need to pass connection string name to DbContext

public class SalesERPDAL: DbContext
{
   public SalesERPDAL() : base("connectionStringName") { }
  public DbSet<Employee> Employees { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().ToTable("TblEmployee");
        base.OnModelCreating(modelBuilder);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM