将数据库加载到对象中

时间:2014-10-06 05:35:29

标签: asp.net asp.net-mvc

所以我尝试使用web.config中的以下内容连接数据库

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

我有一个StoreController类:

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);
    }
}

还有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; }
    }
}

但是当我尝试访问localhost:myportnumber / store / details / 1时,它表示对象引用没有设置为对象的实例,我相信这意味着该应用程序不了解数据库。应用程序是否在启动时自动将数据库加载到对象中?感谢。

1 个答案:

答案 0 :(得分:0)

考虑到上面的代码,我认为你没有打电话给连接并打开它