[英]Database.ExecuteSprocAccessor() not mapping blob data correctly
如果有人可以幫助我解決這個問題,我將不勝感激。 首先,我有一個像這樣的課程:
public class Blob
{
public int BlobID { get; set; }
public string BlobName { get; set; }
public string FileName { get; set; }
public string FileMimeType { get; set; }
public int FileSize { get; set; }
public byte[] FileContent{ get; set; }
public DateTime DateCreated { get; set; }
public int CreatedByProfileID { get; set; }
}
很標准,它只是一個對象,它映射到具有完全相同的字段名稱的表。 SQL Server中的表如下所示:
我的控制器具有添加和查看操作,以對數據庫進行讀取和寫入。 我可以使用以下操作代碼將文件寫得很好:
[HttpPost]
public ActionResult Add(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
Database db = DatabaseFactory.CreateDatabase("dbconnstr");
byte[] fileContent = new byte[file.ContentLength];
file.InputStream.Read(fileContent, 0, file.ContentLength);
object[] paramaters =
{
file.FileName,
file.FileName,
file.ContentType,
file.ContentLength,
fileContent,
DateTime.Now,
12518
};
db.ExecuteNonQuery("sp_Blob_Insert", paramaters);
}
return RedirectToAction("Index");
}
但是,當我使用下面的“查看”操作代碼將文件讀取到瀏覽器中時,“ FileContent”字段始終為null:
public ActionResult View(int id)
{
Database db = DatabaseFactory.CreateDatabase("dbconnstr");
Blob blob = db.ExecuteSprocAccessor<Blob>("sp_Blob_SelectByPkValue", id).Single();
return File(blob.FileContent, blob.FileMimeType, blob.FileName);
}
但是,如果我專門映射字段名稱,則可以使用:
public ActionResult View(int id)
{
Database db = DatabaseFactory.CreateDatabase("dbconnstr");
IRowMapper<Blob> mapper = MapBuilder<Blob>.MapAllProperties().MapByName(x => x.FileContent).Build();
Blob blob = db.ExecuteSprocAccessor<Blob>("sp_Blob_SelectByPkValue", mapper, id).Single();
return File(blob.FileContent, blob.FileMimeType, blob.FileName);
}
這是ExecuteSprocAccessor()函數的錯誤嗎? 我做錯什么了嗎?
謝謝您的時間。
您可以使用以下代碼:
.Map(x => x.FileContent).WithFunc(ConvertVarBinaryToByteArray);
然后創建如下函數:
private static byte[] ConvertVarBinaryToByteArray(IDataRecord dataRecord)
{
return (byte[]) dataRecord.GetValue(dataRecord.GetOrdinal("FileContent"));
}
我這樣解決了這個問題:
在執行ExecuteSprocAccessor之前添加以下代碼:
IRowMapper<FileEmail> rowMapper = MapBuilder<FileEmail>.MapAllProperties()
.Map(x => x.MyFile)
.WithFunc(ConvertVarBinaryToByteArray).Build();
並創建Russ上面所說的方法:
private static byte[] ConvertVarBinaryToByteArray(IDataRecord dataRecord)
{
return (byte[])dataRecord.GetValue(dataRecord.GetOrdinal("FileContent"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.