【问题标题】:Update few Properties of Model after Inserting in database插入数据库后更新模型的一些属性
【发布时间】:2015-03-31 18:18:46
【问题描述】:

在我的ASP.NET Web forms 应用程序中,我有一个Model,其ID 的IDENTITY 类型为int 类型。在我的Insert 中,保存项目后,我创建了该 itemId 的目录并希望在其中保存图像并更新项目中相同的图像路径。在更新项目属性并尝试保存时,它给了我一个错误:-

The property 'ChannelId' is part of the object's key information and cannot be modified.

我的插入方法:

    public void InsertItem()
    {
        Channel item = null;
        item = new Channel();

        TryUpdateModel(item);

        if (ModelState.IsValid)
        {                
            // Save changes
            // After this line only I can get the ID created by DB
            _db.SaveChanges();
            _db.Channels.Add(item);
            System.Diagnostics.Debug.WriteLine("###  EF ID OF Newly Created CHANNEL = " + item.ChannelId);

            // Create Folder for the Channel based on its ID
            string pathToCreate = "~/CRMImages/Channels/" + item.ChannelId;
            string myFileName = "";
            if (!Directory.Exists(Server.MapPath(pathToCreate)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(pathToCreate));
                var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
                System.Security.AccessControl.DirectorySecurity sec = di.GetAccessControl();
                sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
                    System.Security.AccessControl.FileSystemRights.Modify,
                    System.Security.AccessControl.AccessControlType.Allow));
                di.SetAccessControl(sec);

                System.Diagnostics.Debug.WriteLine("CHannel FOLDER CREATED PATH : " + di.FullName);
                myFileName = pathToCreate + "/pancardImg.png";
                System.Diagnostics.Debug.WriteLine("PATH To Save PAN File & NAME : " + myFileName);

                // PAN CARD IMAGE
                FileUpload panInsertUpload = InsertChannelId.FindControl("panInsertUpload") as FileUpload;
                if (panInsertUpload != null)
                {
                    if (panInsertUpload.HasFile)
                    {
                        System.Diagnostics.Debug.WriteLine("EDIT UNIT PLAN FILE NAME =" + panInsertUpload.FileName);
                        myFileName = pathToCreate + "/pancardImg.png";
                        panInsertUpload.SaveAs(Server.MapPath(myFileName));
                        item.PanImageURL = myFileName;
                    }
                }

                TryUpdateModel(item);
                // HERE I GET THE ERROR. HOW TO UPDATE THAT ITEM IN DB
                _db.SaveChanges();
            }
            Response.Redirect("Default");
        }
    }

正在创建目录,正在正确保存文件,我该如何将属性更新到数据库。创建目录并保存文件后,我才能获得要保存的文件路径。

非常感谢任何帮助。 谢谢。

【问题讨论】:

  • TryUpdateModel 有什么用途?
  • 是的,Praveen,我试过了,它奏效了。您可以添加您的答案,以便我可以将其标记为答案。谢谢。
  • 添加了这个效果的答案。

标签: c# asp.net entity-framework model insert-update


【解决方案1】:

在您的示例中,您无需在设置 item.PanImageUrl 后使用 TryUpdateModel。删除此处包含 TryUpdateModel 的部分。

//TryUpdateModel(item);
// HERE I GET THE ERROR. HOW TO UPDATE THAT ITEM IN DB
_db.SaveChanges();

我还注意到您在将 SaveChanges 添加到集合之前调用了它。我觉得应该反过来。

// Save changes
// After this line only I can get the ID created by DB
_db.Channels.Add(item);
_db.SaveChanges();

【讨论】:

  • Praveen,因此对于这种类型的每个更新,它们都不需要 TryUpdateModel()。如何更新 Context 的 DbSet 中已编辑的项目?在其他模型中,除非我手动单击 F5 刷新页面,否则在返回 Default.aspx 时更新不会反映在 DbSet 中。在那个模型中,我在 Edit.aspx 中遇到了这个问题,我以同样的方式重定向到 Default,但这仅在我通过 FileUpload 编辑图像时才会发生,否则不会。
  • 第二个 TryUpdateModel 需要被移除。您使用此方法最初从 Controller 上下文加载实体。您在添加到数据库之前已完成此操作。之后,您可以更新属性并直接调用 SaveChanges
  • 你能帮我解决这个问题吗?stackoverflow.com/questions/29350069/…我无法触发动态添加到表格中的按钮。
【解决方案2】:

将 TryUpdateModel 替换为 TryValidateModel

public void InsertItem()
    {
        Channel item = null;
        item = new Channel();

        TryUpdateModel(item);

        if (ModelState.IsValid)
        {                
            // Save changes
            _db.Channels.Add(item);
            _db.SaveChanges();
            System.Diagnostics.Debug.WriteLine("###  EF ID OF Newly Created CHANNEL = " + item.ChannelId);

            // Create Folder for the Channel based on its ID
            string pathToCreate = "~/CRMImages/Channels/" + item.ChannelId;
            string myFileName = "";
            if (!Directory.Exists(Server.MapPath(pathToCreate)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(pathToCreate));
                var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
                System.Security.AccessControl.DirectorySecurity sec = di.GetAccessControl();
                sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
                    System.Security.AccessControl.FileSystemRights.Modify,
                    System.Security.AccessControl.AccessControlType.Allow));
                di.SetAccessControl(sec);

                System.Diagnostics.Debug.WriteLine("CHannel FOLDER CREATED PATH : " + di.FullName);
                myFileName = pathToCreate + "/pancardImg.png";
                System.Diagnostics.Debug.WriteLine("PATH To Save PAN File & NAME : " + myFileName);

                // PAN CARD IMAGE
                FileUpload panInsertUpload = InsertChannelId.FindControl("panInsertUpload") as FileUpload;
                if (panInsertUpload != null)
                {
                    if (panInsertUpload.HasFile)
                    {
                        System.Diagnostics.Debug.WriteLine("EDIT UNIT PLAN FILE NAME =" + panInsertUpload.FileName);
                        myFileName = pathToCreate + "/pancardImg.png";
                        panInsertUpload.SaveAs(Server.MapPath(myFileName));
                        item.PanImageURL = myFileName;
                    }
                }

                TryValidateModel(item);
                _db.SaveChanges();
            }
            Response.Redirect("Default");
        }
    }

另一个工作代码示例,

[HttpPost]

[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        db.Employees.Add(employee);
        db.SaveChanges();

        int empId = employee.EmployeeID;
        employee.LName = "abc";
        TryValidateModel(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(employee);
}

【讨论】:

  • 谢谢斯米塔。但在 WebForms 中,我只有 TryUpdateModel 而不是 TryValidateModel。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2022-10-01
  • 2016-12-04
  • 2018-03-25
  • 2015-01-26
相关资源
最近更新 更多