Entity Framework 6 not saving changes

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

Question

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();
1
1
7/6/2017 6:41:32 AM

Accepted Answer

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.

0
7/6/2017 11:06:50 AM

Popular Answer

Can you change your code a bit and try following: Rather using db.Advance_Bookings.Add(ab) can you use following:

db.Entry(ab).State = EntityState.Added;

Also, as far my understanding this problem can only occur if the DbContext is disconnected (as it's not giving any error). You can try to wrap your code in a using block

using (var ab = new DbContext()) 
{
//instantiate the object and saveChanges.
}


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