简体   繁体   English

实体框架 6 不保存更改

[英]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.我有一个 MVC5 Web 应用程序,它使用 SQL Server 2008 作为后端数据库以及 Entity Framework 6。添加代码没有错误,但数据无法存储到数据库中。

my model context.cs looks like我的模型 context.cs 看起来像

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();根据评论, 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.Advance_Bookings.Add(ab) 您可以使用以下操作:

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).另外,据我所知,这个问题只有在 DbContext 断开连接时才会发生(因为它没有给出任何错误)。 You can try to wrap your code in a using block您可以尝试将代码包装在 using 块中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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