Reputation: 1748
I have the following two classes generated by Entity Framework..
public partial class Datagrid
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public Nullable<bool> IsChecked { get; set; }
}
public partial class SampleDbContext : DbContext
{
public SampleDbContext()
: base("name=SampleDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Datagrid> Datagrids { get; set; }
}
i have a WPF application where I have a list view containing checkboxs for each column.. I have written the to logic to find what are the checkboxes that are checked in the list view.. But when I iterate through the checked boxes and try to save to the database, database is not updating please help.. dg is object of type Datagrid.. db is object of type SampleDbContext
foreach (CheckBox cb in myBoxes)
{
dg.IsChecked = cb.IsChecked; //I want to update each column with the checked value in the listview. cb.Ischecked works perfectly..It says true for the checkboxes that are checked else false
db.SaveChanges(); //NOT updating the database
}
Upvotes: 2
Views: 157
Reputation: 2590
Based on your comments, I'm not entirely clear on if the checkboxes need to be created each time or just updated. If created, it will be somewhat like the other answer. However, you were likely getting the System.Data.Entity.Validation.DbEntityValidationException
due to attempting to add a new Datagrid without providing a Name
and Location
, which are not nullable and are not (presumably) automatically populated like Id
:
foreach (CheckBox cb in myBoxes)
{
Datagrid dg = new Datagrid
{
Name = "NameGoesHere"; // Maybe you're wanting to use cb.Name or cb.Text?
Location = "Location Here";
IsChecked = cb.IsChecked;
};
db.DataGrids.Add(dg);
db.SaveChanges();
}
If you're just updating instead, I'm still not sure where you're setting dg
, but perhaps you might want to look it up from :
foreach (CheckBox cb in myBoxes)
{
Datagrid dg = db.DataGrids.Where(g => g.Name == cb.Name).SingleOrDefault();
// etc.
Edit based on comments:
If you're doing two-way binding and have directly bound CheckBox
es to the IsChecked
values of Datagrid
entities, you shouldn't need to do anything other than simply call db.SaveChanges();
when you're ready to save. The bound Datagrid
entities will be updated on their own.
Upvotes: 1
Reputation: 1690
Your variable 'dg' will need to be part of the databaseContext's ('db' in your code) DataGrid's Property. An example:
foreach (CheckBox cb in myBoxes)
{
dg.IsChecked = cb.IsChecked;
db.DataGrids.Add(dg);
db.SaveChanges();
}
.SaveChanges() will only flush items assigned to the DataGrid property to the database.
Upvotes: 1