读书人

Entity Framework 4.0 怎么更新对象

发布时间: 2013-06-26 14:29:32 作者: rapoo

Entity Framework 4.0 如何更新对象
我要在方法里传入一个对象,用这个对象去更新数据库里的对角。
代码如下:
public int UpdateNewsDoc(NewsDoc nd, EntityCollection<NewDocAttachments> Attachments, EntityCollection<InNewsPicSwf> InNewsPicSwfs)
{
try
{
using (var db = new JiXiaoWebSite_DAXLJWEntities())
{
if (Attachments != null && Attachments.Count > 0)
{
IList<NewDocAttachments> DelAttachmentsList = Attachments.Where(a => a.IsDel == true).ToList();
while (DelAttachmentsList.Count > 0)
{
if (FileHelper.IsExistFile(HttpContext.Current.Server.MapPath(DelAttachmentsList.ElementAt(0).AttachmentsURL.Trim() + DelAttachmentsList.ElementAt(0).AttachmentsName.Trim())))
{
FileHelper.DeleteFile(HttpContext.Current.Server.MapPath(DelAttachmentsList.ElementAt(0).AttachmentsURL.Trim() + DelAttachmentsList.ElementAt(0).AttachmentsName.Trim()));
}
Attachments.Remove(DelAttachmentsList.ElementAt(0));
DelAttachmentsList.Remove(DelAttachmentsList.ElementAt(0));
}
}

if (InNewsPicSwfs != null && InNewsPicSwfs.Count > 0)
{
IList<InNewsPicSwf> DeInNewsPicList = InNewsPicSwfs.Where(a => a.IsDel == true).ToList();


while (DeInNewsPicList.Count > 0)
{

if (FileHelper.IsExistFile(HttpContext.Current.Server.MapPath(DeInNewsPicList.ElementAt(0).FileURL.Trim() + DeInNewsPicList.ElementAt(0).FileName.Trim())))
{

FileHelper.DeleteFile(HttpContext.Current.Server.MapPath(DeInNewsPicList.ElementAt(0).FileURL.Trim() + DeInNewsPicList.ElementAt(0).FileName.Trim()));

}
InNewsPicSwfs.Remove(DeInNewsPicList.ElementAt(0));
DeInNewsPicList.Remove(DeInNewsPicList.ElementAt(0));
}
}

nd.NewDocAttachments = Attachments;
nd.InNewsPicSwf = InNewsPicSwfs;

如何将nd 更新到库里?
db里有NewsDoc 表属性,NewsDoc里又包括两个列表属性NewDocAttachments ,
InNewsPicSwf ,分别为与NewsDoc的相关联的表。 return db.SaveChanges();
}

}
catch (Exception ex)
{
Log4Helper.ErrorFormat(CommonParameters.ErrorMessage, "更新NewsDoc", ex.Message, ex.StackTrace);
throw ex;
}
}

Entity?Framework?4 更新对象?
[解决办法]
上了一坨代码,不知道你想问什么
[解决办法]
直接查询DataContext得到对象,修改它的属性,最后调用DataContext.SaveChanges()方法即可。
[解决办法]
你看看你的context是不是ObjectContext
如果是
把objectContext变成DbContext
public DbContext(ObjectContext objectContext,
bool dbContextOwnsObjectContext)
{}

读书人网 >.NET

热点推荐