简体   繁体   English

无法将实体对象保存到数据库

[英]Can not save entity object to database

I am trying to edit an already added entity object. 我正在尝试编辑一个已经添加的实体对象。

The model I use for Entity Frameworks` Code First (or Model First, what ever you prefer), is the following: 我用于实体框架的“代码优先”(或“模型优先”,无论您喜欢哪种)的模型如下:

public class ImageFile
{
    public int Id { get; set; }
    [DisplayName("Naam")]
    public string FileName { get; set; }

    public string ImageUrl { get; set; }
}

In the view I hide the ImageUrl and allow the user to upload a file, which works correctly. 在视图中,我隐藏了ImageUrl并允许用户上载正确运行的文件。 After the change of image has happend (this is an Edit method), I want to save the object back into the database. 更改图像后(这是一个Edit方法),我想将对象保存回数据库中。

The following method demonstrates: 以下方法演示:

public ActionResult Edit([Bind(Include = "Id,FileName,ImageUrl")] ImageFile imageFile, HttpPostedFileBase actualImage)
{
    if(actualImage != null && actualImage.ContentLength > 0)
    {
        ImageFile originalImageFile = db.Images.Find(imageFile.Id);
        if(originalImageFile.FileName != imageFile.FileName)
        {
            DeleteImage(originalImageFile.FileName);
        }
        string fullUrl = SaveImage(imageFile, actualImage);

        // Set the new imageUrl.
        imageFile.ImageUrl = fullUrl.Replace("~", "");

        // Save changes to database
        var entry = db.Entry(imageFile);
        entry.Property(i => i.ImageUrl).IsModified = true;
        entry.Property(i => i.FileName).IsModified = true;
        db.SaveChanges();

        return RedirectToAction("Index");
   }

   // Else that only changes the filename, instead of uploading a new file.
   // Uses same saving logic.

}

As you can see I have changed from the original Edit-savechanges that MVCs' scaffolding created for me. 如您所见,我已经改变了MVC支架为我创建的原始Edit-savechanges。 It is something like: 就像这样:

db.Entry(imageFile).State = EntityState.Modified;
db.SaveChanges();

Both solutions didn't work. 两种解决方案均无效。 The first solution throws an InvalidOperationException : 第一个解决方案抛出InvalidOperationException

Additional information: Member 'IsModified' cannot be called for property 'ImageUrl' because the entity of type 'ImageFile' does not exist in the context. 附加信息:无法为属性“ ImageUrl”调用成员“ IsModified”,因为上下文中不存在“ ImageFile”类型的实体。 To add an entity to the context call the Add or Attach method of DbSet. 要将实体添加到上下文,请调用DbSet的Add或Attach方法。

The second solution also throws an InvalidOperationException : 第二种解决方案还引发InvalidOperationException

Additional information: Attaching an entity of type 'BonTemps.Areas.Admin.Models.ImageFile' failed because another entity of the same type already has the same primary key value. 附加信息:附加类型为'BonTemps.Areas.Admin.Models.ImageFile'的实体失败,因为相同类型的另一个实体已经具有相同的主键值。 This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. 如果图形中的任何实体具有相互冲突的键值,则使用“附加”方法或将实体的状态设置为“不变”或“修改”时,可能会发生这种情况。 This may be because some entities are new and have not yet received database-generated key values. 这可能是因为某些实体是新实体,尚未收到数据库生成的键值。 In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. 在这种情况下,请使用“添加”方法或“已添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。

I am really stuck here and have no idea what I can do to save the changes. 我真的被困在这里,不知道该怎么做才能保存更改。 Why will it not save? 为什么不保存? Does it have anything to do with me setting the ImageUrl manually, after entering the ActionResult method? 输入ActionResult方法后,手动设置ImageUrl与我有什么关系吗?

Should I create a ViewModel instead, and manually do the changes? 我应该改为创建ViewModel并手动进行更改吗? Is there any solution in which I can avoid creating a ViewModel for this? 有什么解决方案可以避免为此创建ViewModel?

Instead of trying to tell EF that you have changed the properties, use the db Entity that you just pulled from the DB. 与其尝试告诉EF您已经更改了属性,不如使用刚从数据库中拉出的db Entity。 So the place that you have 所以你有的地方

// Save changes to database
var entry = db.Entry(imageFile);
entry.Property(i => i.ImageUrl).IsModified = true;
entry.Property(i => i.FileName).IsModified = true;
db.SaveChanges();

Would change to 将更改为

// Save changes to database
originalImageFile.ImageUrl = imageFile.ImageURL;
originalImageFile.FileName = imageFile.FileName;
db.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM