Reputation: 1229
I'm trying to add more tables to DefaultConnection database in my MVC project, using code first approach.
I have the following setup:
MyClass.cs
public class MyClass
{
public int Id { get; set; }
public string Name{ get; set; }
public int Age{ get; set; }
}
MyClassController.cs
public class MyClassController : Controller
{
public MyClassDbContext myClassDbContext = new MyClassDbContext();
public ActionResult Index()
{
return View(myClassDbContext.MyClasses.ToList());
}
}
MyClassDbContext.cs
public class MyClassDbContext: DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
I have not changed ConnectionString
from its default settings since it is the same database that works with user registration and authentication and I have no issues with it.
After running code I get A network related or instance-specific error occurred while establishing a connection to SQL Server...
error on return View(myClassDbContext.MyClasses.ToList())
.
Question:
Am I missing something basic?
Upvotes: 0
Views: 1239
Reputation: 274
public class MyClassDbContext: DbContext
{
public MyClassDbContext(string connString)
: base(connString)
{
}
public DbSet<MyClass> MyClasses { get; set; }
}
public class MyClassController : Controller
{
public MyClassDbContext myClassDbContext = new MyClassDbContext("Name Of ConnectionString");
public ActionResult Index()
{
return View(myClassDbContext.MyClasses.ToList());
}
}
for adding more table you need to use constructor. above code helps you to make it working.
Upvotes: 2
Reputation: 90
Please check the connection string in web.config and see if it is valid.Also make sure that the SQL Server is already connected.
Upvotes: -2
Reputation: 481
When you add a model
e.g MyClass
, you don't need add a new DBContext
e.g MyClassDbContext
, you just add MyClass
to your exist DBContext
which work for your registration. someting like this:
public class OldDbContext: DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
public DbSet<User> Users{ get; set; }
}
Then you need add a Initializer
to auto generatge table(more check this), or you can add table by youself it'll work if table is match to you class.
Upvotes: 1