Sto cercando di aggiornare una proprietà virtuale utilizzando EF6 e MVC. Il mio codice è così:
public async Task<ActionResult> Edit([Bind(Include = "Id,Title,Content,Image")] Recommendation recommendation, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
//we have an image - saving it to db
var image = Server.SaveFile(file, Request);
DB.Files.Add(image);
await DB.SaveChangesAsync();
//assign the new image to the recommendation
recommendation.Image = image;
}
recommendation.User = await GetLoggedInUserAsync();
DB.Entry(recommendation).State = EntityState.Modified;
await DB.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(recommendation);
}
L'immagine viene salvata nella tabella Files
. Tuttavia, la colonna Image_Id
nella tabella dei Recommendations
non si aggiornerà al nuovo Image_Id
. Cosa mi manca qui?
Classi:
public class Item
{
[Key]
public int Id { get; set; }
public virtual ApplicationUser User{ get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Content")]
public string Content { get; set; }
}
public class Recommendation : Item
{
[DisplayName("Image")]
public virtual File Image { get; set; }
}
public class File
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
Il problema è che stai lavorando con un'associazione indipendente (che non ha ID di chiave esterna), come.
public int ImageId { get; set; }
E tu lavori anche con oggetti disconnessi. Quindi è necessario mantenere la relazione manualmente. Devi anche eliminare la vecchia relazione prima di aggiungere una nuova relazione.
Se si sta lavorando con oggetti disconnessi, è necessario gestire manualmente la sincronizzazione. - MSDN
Prova ad aggiungere questo codice per gestire manualmente la relazione.
var manager = ((IObjectContextAdapter)DB).ObjectContext.ObjectStateManager;
// Removes previous relationship.
if (recommendation.Image != null)
{
// If there is another image, but you don't remove it, the update will fail.
manager.ChangeRelationshipState(recommendation, recommendation.Image,
r => r.Image, EntityState.Deleted);
}
// Adds new relationship.
manager.ChangeRelationshipState(recommendation, image,
r => r.Image, EntityState.Added);
Prova a riconsiderare il design della classe per avere l'associazione delle chiavi esterne.
Vedi questo post per ulteriori informazioni.