0

如果任何人都可以幫我弄清楚這一點,我將不勝感激。對於初學者來說,我有一個類,像這樣:Database.ExecuteSprocAccessor()沒有正確映射blob數據

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中的表看起來像這樣:

enter image description here

我的控制器具有添加和查看行動做讀取和寫入到數據庫。我可以寫文件很好,使用下面的操作代碼:

[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場總是空:

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()函數中的錯誤?我做錯了什麼?

感謝您的時間提前。

+0

您是否找到了答案?我有同樣的問題 – ydd1987

+0

我沒有,我也沒有任何運氣谷歌搜索... – ryanulit

回答

0

您可以使用下面的代碼:

.Map(x => x.FileContent).WithFunc(ConvertVarBinaryToByteArray); 

然後,像這樣創建功能:

private static byte[] ConvertVarBinaryToByteArray(IDataRecord dataRecord) 
{ 
    return (byte[]) dataRecord.GetValue(dataRecord.GetOrdinal("FileContent")); 
} 
0

我解決了這個問題是這樣的:

添加該代碼執行前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")); 
    }