在数据库中插入后更新少数模型属性

时间:2015-03-31 07:38:29

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

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

正在创建目录,正在保存文件,我该如何更新数据库的属性。创建dir&仅保存文件我可以保存文件路径。

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

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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