0

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?

1
  • Set a breakpoint on this.Database.Exists() line and see if the DB exist there. If the error says "Server not found", you need to configure SQL Server connection string on web.config file. Commented Nov 2, 2016 at 5:48

3 Answers 3

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

This solved my error. I was not calling the base constructor.
1

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.

Comments

-2

Please check the connection string in web.config and see if it is valid.Also make sure that the SQL Server is already connected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.