mysql fields look like:
Entity Framework with mysql on existting database
my application is a mvc 4 project using EF 4.4 on mysql with a existting database.
how can i just update a part of then fields when table 's all fields are not nullable but have default value . when create or update persistent to database for a part of field, EF will Automatically fill a null to those do not explicitly specified fields and i will get a exception.
i don't want modify database. what can i go with this? thank you
Edit:
my code like this... how make changes to it in your opinion?
[HttpPost]
public ActionResult Edit(Post_15 post)
{
if (ModelState.IsValid)
{
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
You must provide default values to your object (for example in constructor). EF doesn't play nicely with database default values. With default update EF always sends explicit value for each column. When you send explicit value, the default value the database is not used. If you don't set the value for property in the application, .NET default value is send to database.
Alternatively you must handle update in completely different way. You must explicitly set columns you are going to update to ensure that EF will not update other columns.
var entity = new YourEntity {
Id = 123,
ColumnToUpdate = "ABC"
};
objectContext.Attach(entity);
ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);
entry.SetModifiedProperty("ColumnToUpdate");
objectContext.SaveChanges();
This code will update only ColumnToUpdate
even if there are 20 other persisted properties.
Edit:
DbContext alternative:
var entity = new YourEntity {
Id = 123,
ColumnToUpdate = "ABC"
};
dbContext.Entities.Attach(entity);
DbStateEntry<Entity> entry = dbContext.Entry(entity);
entry.Property(e => e.ColumnToUpdate).IsModified = true;
dbContext.SaveChanges();
Side note: Only .NET 4.5 supports setting IsModified
back to false.