Create table in Database using Entity Framework

asp.net-mvc c# entity-framework

Question

I'm trying to link my MVC project with a database using Entity Framework, but I can't figure out how to store new records to a database. So far I have the following code:

//model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MvcApplication1.Controllers;

namespace MvcApplication1.Models
{
public class CarUser
{
    public int ID { get; set; }
    [DisplayName ("First Name")]
    public string Fname { get; set; }
    [DisplayName ("Surname")]
    public string Sname { get; set; }
}
}

//controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
public class CarUserController : Controller
{
    private FormDataContext db = new FormDataContext();

    //
    // GET: /CarUser/

    public ActionResult Index()
    {
        return View(db.CarUsers.ToList());
    }

    //
    // GET: /CarUser/Details/5

    public ActionResult Details(int id = 0)
    {
        CarUser caruser = db.CarUsers.Find(id);
        if (caruser == null)
        {
            return HttpNotFound();
        }
        return View(caruser);
    }

    //
    // GET: /CarUser/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /CarUser/Create

    [HttpPost]
    public ActionResult Create(CarUser caruser)
    {
        if (ModelState.IsValid)
        {
            db.CarUsers.Add(caruser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(caruser);
    }

    //
    // GET: /CarUser/Edit/5

    public ActionResult Edit(int id = 0)
    {
        CarUser caruser = db.CarUsers.Find(id);
        if (caruser == null)
        {
            return HttpNotFound();
        }
        return View(caruser);
    }

    //
    // POST: /CarUser/Edit/5

    [HttpPost]
    public ActionResult Edit(CarUser caruser)
    {
        if (ModelState.IsValid)
        {
            db.Entry(caruser).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(caruser);
    }

    //
    // GET: /CarUser/Delete/5

    public ActionResult Delete(int id = 0)
    {
        CarUser caruser = db.CarUsers.Find(id);
        if (caruser == null)
        {
            return HttpNotFound();
        }
        return View(caruser);
    }

    //
    // POST: /CarUser/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        CarUser caruser = db.CarUsers.Find(id);
        db.CarUsers.Remove(caruser);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}
}

//formdatacontext

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcApplication1.Models
{
public class FormDataContext : DbContext
{
    public DbSet<CarUser> CarUsers
    { get; set; }
}
}

//formdatainitialiser

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.IO;

namespace MvcApplication1.Models
{
public class FormDataInitializer : DropCreateDatabaseAlways<FormDataContext>
{
    protected override void Seed(FormDataContext context)
    {
        base.Seed(context);

        var CarUsers = new List<CarUser>
        {
            new CarUser {
                ID = 1,
                Fname = "Craig",
                Sname = "Higginson",
            }
        };

        CarUsers.ForEach(s => context.CarUsers.Add(s));
        context.SaveChanges();

        }
    }

}

I've also got the following in my web.config file

<connectionStrings>
<add name="FormDataContext"
     connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=FormData.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

This all builds fine, and when I navigate to /caruser i am able to create new records. These records aren't being stored in my database.

Do I need to create the table in the database first or should Entity Framework create this for me, if i have referenced the database correctly?

1
3
12/10/2013 6:16:28 AM

Accepted Answer

If you're using a Code First approach then Entity Framework will build the table for you. It looks like you are not using Code First, so you will have create the table in the database. I assume you're using an Entity Data Model (.edmx)? If so, you will create your table in the database, then update your data model (.edmx). If you have not yet created your .edmx file, you need to do that - the .edmx file will contain all your CRUD operations.

What I'm confused about is I'd imagine your code would throw an error if the table did not exist (i.e. if the table represented by your data model didn't map to an actual table in the database, because it doesn't exist). So, the question is, does your table already exist? If it does, then step through the code line by line to find out why your records aren't being saved. If it doesn't exist, then add the table via SQL Server Management Studio (or similar), then open your .edmx file, right click on the layout that comes up, click "Update Model from database".

1
12/9/2013 4:23:03 PM

Popular Answer



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow