【发布时间】: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