Search code examples
c#entity-framework-6asp.net-mvc-5savechanges

Entity Framework 6 not saving changes


I've got an MVC5 web application that uses SQL Server 2008 as a back end database along with the Entity Framework 6. There's no error in adding code but data can not get stored in to database.

my model context.cs looks like

public partial class checkin_checkoutEntities2 : DbContext
    {
        public checkin_checkoutEntities2()
            : base("name=checkin_checkoutEntities2")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Advance_Booking> Advance_Bookings { get; set; }
        public virtual DbSet<employee_reg> employee_reg { get; set; }
        public virtual DbSet<Extend_Stay> Extend_Stay { get; set; }
        public virtual DbSet<Guest_reg> Guest_reg { get; set; }
        public virtual DbSet<RoomBooking> RoomBooking { get; set; }
        public virtual DbSet<Rooms_ms> Rooms_ms { get; set; }
    } 

and my adding method is as below

 ab.Room_id = Convert.ToInt32(ab_rm_no.room_id);
 ab.Guest_id = Convert.ToInt32(frm["guest_id"].ToString());
 ab.Expected_checkin  = Convert.ToDateTime(frm["BookedDateFR"].ToString());
 ab.Expected_checkout = Convert.ToDateTime(frm["BookedDateTO"].ToString());
 
 db.Advance_Bookings.Add(ab);
 db.SaveChanges();

Solution

  • According to the comments, the db.SaveChanges(); was wrapped in a transaction

    using (var transaction = new System.Transactions.TransactionScope())
    {
        // some changes and db.SaveChanges();
    }
    

    and it was working only without the transaction.

    The reason is, that a transaction needs to be committed in order to persist the saved changes.

    using (var transaction = new System.Transactions.TransactionScope())
    {
        // some changes and db.SaveChanges();
    
        transaction.Commit();
    }
    

    Otherwise the changes would be discarded at the end of the transaction block.