Gibraltar Support

Start a new topic

Entity Framework noob

This is my first foray into EF. The following code persists the customer, but the customer.ID field is not updated with the new PK value.


Is there something I've missed.


 

public Customer AddCustomer(Customer customer)
{
            using (var entities = new HillStationEntities())
            {
                entities.Customers.Add(customer);
                entities.SaveChanges();
                return customer;
            }
}


// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace HillStationPOS.Model.Entities
{
    using System;
    using System.Collections.Generic;
    
    public partial class Customer
    {
        public int Id { get; set; }
        public string Details { get; set; }
    }
}

 



All I did was change the structure of the table and it works now, Cheers.

What you need to do is refresh the entity before returning it.

When you want to get back whatever the database has for an item - such as for an auto-added ID - you need to tell EF to refresh that entity before returning it.  Assuming that entities is your DbContext you can do entities.Entry(customer).Reload();


Still the same, note Kendall Miller (new customer) has been added to the collection of customers in the after image:


Before:




After:


Did you look at the DB and confirm that you have auto identity set for the Id column?

Yes, new records are added with an incrementing PK

Login to post a comment