Breece
Breece

Reputation: 31

Beginner to Entity Framework

I am a beginner to Entity Framework.

I am learning using a tutorial.

The application consists in two fields and a submit button that are supposed to be added in a SQL SERVER EXPRESS database.

It seems that there is no interaction with the database at all. I do not know where to start because I have no error message since I corrected the one more below.

my model :

public class Customer
{
    [Key]
    [Required]
    public int CustomerCode { get; set; }

    [Required]
    [StringLength(10)]
    [RegularExpression("^[A-Z]{7,7}$")]
    public string CustomerName { get; set; }
}

my connection string in the web.config file :

<connectionStrings>
<add 
  name="CustomerDal" 
  connectionString="Data Source=localhost\SQLExpress;Initial Catalog=MVC2db;Integrated Security=True"
  providerName=".NET Framework Data Provider for SQL Server" 
  />

My Db context :

public class CustomerDal : DbContext 
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Customer>().ToTable("tblCustomer");
    }

    public DbSet<Customer> Customer { get; set; }

}

the Submit action :

public ActionResult Submit(
// [ModelBinder(typeof(CustomerBinder))]
Customer obj) //validation runs 
{
 //   Customer obj = new Customer();

   // obj.CustomerCode = Request.Form["CustomerCode"];
  //  obj.CustomerName = Request.Form["CustomerName"];
      if (ModelState.IsValid)
      {
          CustomerDal Dal = new CustomerDal();
          Dal.Customer.Add(obj);     //in memory
          Dal.SaveChanges();          //physical commit 

          return View("Customer", obj);
      }
      else
      { 
          return View("EnterCustomer", obj);
      }
}

EnterCustomer.cshtml, where obj comes from

' @using (Html.BeginForm("Submit", "Customer", FormMethod.Post)) {

        <i>Customer Name : </i> @Html.TextBoxFor(m => m.CustomerName)

    <br>
    @Html.ValidationMessageFor(x => x.CustomerName)
    <br>

        <i>Customer Code : </i> @Html.TextBoxFor(m => m.CustomerCode)

            <br>
            @Html.ValidationMessageFor(x => x.CustomerCode)
            <br>
            <input id = "Submit1" type = "submit" value = "submit"/>

            }

'

I have got a first error message about a duplicate key during the SaveChanges. After some research I added this line in the global.asax file : Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

Since then I do not have any error message but nothing happen when I enter a new item.

Upvotes: 0

Views: 1089

Answers (3)

Fabulous
Fabulous

Reputation: 2423

The key in your model is an integer and by default is 0. When you save to the database, only one row can have that key. You must go to the table design and set the CustomerCode column to be an Identity Column to make it auto increment when new records come in. With your existing code, Entity Framework will retrieve the newly created key and put it in your CustomerCode property so you can use it in other places in your code if you wish.

You mention that you added DropCreateDatabaseIfModelChanges when trying to solve the problem; I believe this is unnecessary and might have unwanted effects when you change your model in future.

Upvotes: 1

BWA
BWA

Reputation: 5764

Popably in

public ActionResult Submit(
// [ModelBinder(typeof(CustomerBinder))]
Customer obj) //validation runs 

you get empty object or null. So you add nothing to dbContext so nothing to save.

Debug app and check value in obj parameter.

Upvotes: 0

Hemal
Hemal

Reputation: 3760

You are creating a new blank object of type CustomerDal and saving it. You already have all the values in the binded object obj

    if (ModelState.IsValid)
    {
        //CustomerDal Dal = new CustomerDal();//REMOVE THIS LINE
        Dal.Customer.Add(obj);     //in memory
        Dal.SaveChanges();          //physical commit 

        return View("Customer", obj);
    }
    else
    { 
        return View("EnterCustomer", obj);
    }

Upvotes: 0

Related Questions