user3768179
user3768179

Reputation: 61

Entity framework doesn't update the bit value

I have a strange problem with entity framework, In my project im using EF 6 codefirst and for my database im using sqlserver 2012

as with a table iam using isactive column of type bit, which represents 0 or 1 only. and defaultly i kept this column value as 1 which is represents true.

When we want to delete a record from the table we should have to make 1 to 0, but the entity framework doesn't updating the value.

is any one having this strange problem any 1 with solution here ??

Code:

 using (var context = new TriviaContext())
            {

                var booking = context.Booking.FirstOrDefault(b => b.BookingId == id);
                context.Entry(booking).Property(u => u.IsActive).IsModified=true;
                booking.IsActive = false;


                context.SaveChanges();

                return Ok(booking);
            }

Booking Model:

class Booking
{
 public int BookingId { get; set; }
 public string Name{get;set;}
 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
 public bool? IsActive { get; set; }
}

edit: actually i have included DatabaseGenerated Attribute in my model class, may be this is causing the problem ?

TriviaContext:

public class TriviaContext : DbContext
{
    public TriviaContext()
        : base("name=DefaultConnection")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
    public DbSet<Bookings> Booking { get; set; }
}

Upvotes: 4

Views: 2086

Answers (3)

user3768179
user3768179

Reputation: 61

well i was using [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attribute for default generate the value , but this is causing me that The Entity Framework dint generating the sql to update the records , so when i remove this attribute the EF able to generating the updating things.so i could go with my work for now. but this kinda coding is right or wrong ... any experienced guys can suggest me for this kinda problems to solve....

Regards BosH

Upvotes: 2

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

The entity is loaded and tracked, so no need to use the Entry method to change the property value, just change and save the entity

using (var context = new TriviaContext())
            {

                var booking = context.Booking.Find(id);
                booking.IsActive = false;
                context.SaveChanges();

                return Ok(booking);
            }

Upvotes: 0

this.hart
this.hart

Reputation: 328

Try this:

     using (var context = new TriviaContext())
        {
       var booking  = (from x in context.Booking
         where x.BookingId == id
         select x).First();

            booking.IsActive = false;
            context.SaveChanges();

            return Ok(booking);
        }

Upvotes: 0

Related Questions