插入数据库后更新模型的一些属性

Update few Properties of Model after Inserting in database

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

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");
        }
    }

正在创建目录,正在保存文件,请问如何更新数据库的属性。创建目录并保存文件后,我只能获取要保存的文件路径。

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

在您的示例中,您无需在设置 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();

用 TryValidateModel 替换 TryUpdateModel

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);
}