0

正如问题所暗示的,我想将图像存储到文件系统中并将指向它的链接保存在数据库中。但 NHibernate 不会将文件路径保存在数据库中。这是代码:

[HttpPost]
    public ActionResult Edit(Item item, HttpPostedFileBase image)
    {
        if (ModelState.IsValid)
        {
            if (image != null)
            {
                string imageName = image.FileName;
                string location = Path.Combine(Server.MapPath("~/Content/Images/ItemImages/") , imageName);
                image.SaveAs(location);
                item.Image= imageName;
            }

            menuItemRepository.SaveOrUpdate(item);
// here the debug show the image path has correctly assigned to the image property
                Debug.WriteLine(item.Image);
                TempData["message"] = string.Format("{0} has been saved", item.Name);
                return RedirectToAction("Index", item.Parent);
            }
            else
            {
                // there is something wrong with the data values 
                return View(Item);
            }
        }

但是在存储库保存或更新项目后,当我查看数据库时,图像为空。我试图分配像图像名称这样的元素,它确实有效,但图像路径不起作用!我很困惑为什么会这样。有人有什么主意吗?

   public class Item
{
  public virtual string Image { get; set; } 
} 

public calss ItemMap : ClassMap<Item>
{
  public ItemMap()
{
Map(x => x.Image).Length(100);
}
}

//////////存储库

 public T SaveOrUpdate(T entity)
    {
        session.SaveOrUpdate(entity);
        return entity;
    }
4

2 回答 2

0

我已经为我的 MVC 应用程序实现了 sessionPreRequest 模块。所以我在那里做 commit() 操作。我检查并看到我的事务没有提交并且正在回滚。并检查错误,数据库中的图像列是nvarchar(50),但是具有图像路径的字符串超过50个字符。所以我改为nvarchar(200)现在一切正常。

于 2013-11-03T13:43:02.050 回答
0

我最好的猜测 - 保存没有被刷新到数据库。请参阅文档

将不时ISession执行将 ADO.NET 连接状态与内存中保存的对象状态同步所需的 SQL 语句。这个过程,flush,默认发生在以下几点

  • 从某些调用Find()Enumerable()
  • NHibernate.ITransaction.Commit()
  • ISession.Flush()

我在您的代码中看不到任何会触发刷新的内容。SaveOrUpdate将您的交易包装起来:

using (var trx = menuItemRepository.BeginTransaction())
{
    menuItemRepository.SaveOrUpdate(item);
    trx.Commit();
}

trx.Commit()会将挂起update的查询刷新到数据库。

于 2013-11-01T20:44:33.600 回答