0

So I'm trying to connect to a database using the following in my web.config

    <connectionStrings>
        <add name="StoreEntities"
        connectionString="Data source=localhost;Initial Catalog=testdb;Integrated           Security=True" <providerName="System.Data.SqlClient" />
    </connectionStrings>

I have a StoreController class:

public class StoreController : Controller
{
    StoreEntities storeDB = new StoreEntities();

    // Index does nothing atm
    public ActionResult Index()
    {
        return View(categories);
    }

    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Product product = storeDB.Products.Find(id);
        return View(product.Title);
    }
}

And also StoreEntities:

using System.Data.Entity;

namespace Assignment_2.Models
{
    public class StoreEntities : DbContext
    {
        public StoreEntities(): base("StoreEntities")
        {

        }

        public DbSet<Product> Products    { get; set; }
        public DbSet<Category> Categories { get; set; }
    }
}

But when I try and visit localhost:myportnumber/store/details/1 it says object reference not set to an instance of an object which I believe means that the app doesn't know about the database. Does the app automatically load the database into objects on startup? Thanks.

Teddy
  • 19
  • 1
  • 5
  • First of all, have you checked with the debugger which instance causes the NullReferenceException? That should lead you to the cause of the problem. Regarding your other question: no, Entity Framework (or any ORM for that matter) won't load data until you explicitly ask for it by querying. It might cache some of the loaded data within the same session, though. – Wim.van.Gool Oct 06 '14 at 05:48
  • What is the value of `product.Title` ? – Ofiris Oct 06 '14 at 05:55
  • That error could be anything - the only way to find out what is to debug and find the line it occurs on. – Nick.Mc Oct 06 '14 at 06:05
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – शेखर Oct 06 '14 at 06:34

1 Answers1

0

Considering above code i think you are not calling to connection and open it

tharinda
  • 9
  • 7