简体   繁体   中英

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();

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.

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM