I recently worked through Steve Sanderson's Pro ASP.NET MVC Framework and ran into an issue with the sample "SportsStore" application. SportsStore is a simple CRUD app that provides an editor to insert and update products in the store. Each product can have an image (which is stored in a SQL Server database, I know, maybe not the best idea but that's a debate for another thread).
The issue that I noticed is that when you update a product, if the product has an image, you lose the product image. This is happening because the code doing the updating is looking for fields that have changed compared to what's currently in the database. When the DataContext sees that the file upload dialog from the product update form is empty, it sets the ImageData and ImageMimeType fields to null. What I'm hoping to do is tell the DataContext not touch the ImageData and ImageMimeType fields if you're doing an update and the file upload dialog content is empty. Here's the current code that writes changes to the database:
public void SaveProduct(Product product)
{
EnsureValid(product, "Name", "开发者_如何学编程Description", "Category", "Price");
// If it's a new product, just attach it to the DataContext
if (product.ProductID == 0)
productsTable.InsertOnSubmit(product);
else {
// If we're updating an existing product, tell the DataContext
// to be responsible for saving this instance
productsTable.Attach(product);
// Also tell the DataContext to detect any changes since the last save
productsTable.Context.Refresh(RefreshMode.KeepCurrentValues, product);
}
productsTable.Context.SubmitChanges();
}
If I need to post more, just let me know. You can download all the source code for this app from the book's site. The app is in the "Chapter 04 to 06 - SportsStore" directory.
Being an ASP.NET MVC noob, I'm not sure if my idea of trying to tell the DataContext to not update specific fields is correct. If anyone else has a better plan, I'm open to ideas. The goal is to preserve the image in the database on updates.
Maybe this is the opposite of my problem here; try changing the key line to:
memberCache.Set(metaMember.Ordinal, false);
You should be able to use this by overriding SubmitChanges
in your data-context:
public override void SubmitChanges(ConflictMode failureMode)
{
foreach(object obj in GetChangeSet().Updates) {
// toggle
}
base.SubmitChanges(failureMode);
}
精彩评论