試試這個:
public ActionResult Create(Lugar lugar, HttpPostedFileBase fotosLugar)
{
if (fotosLugar != null && fotosLugar.ContentLength > 0)
{
var contentLength = fotosLugar.ContentLength;
var content = new byte[contentLength];
fotosLugar.InputStream.Read(content, 0, contentLength);
var foto = new Foto { Binary = content };
lugar.FotosLugar = foto;
}
//... eventually return an ActionResult
}
文件是因爲字節包含在Stream
對象有點棘手,處理比正常的數據。上面的代碼從流中讀取字節,以便它們可以存儲在EF實體類中。
一對夫婦的其他注意事項:這也許不是一個壞主意,還存放了ContentLength
,ContentType
,並在您Foto
實體可能FileName
。您可能還想考慮將此實體分解爲2,以便可以從原始二進制文件數據中分別查詢文件名,內容類型和內容長度。我們在我們的網站中遇到了一個問題,我們只需要獲取文件名,但該查詢速度很慢,因爲我們將byte[]
列存儲在與文件名相同的表上,所以SQL在我們所有的時候都返回了所有的二進制數據需要的是字符串文件名。最終解決了類似以下的模型:
public class Foto
{
public int Id { get; set; }
public int ContentLength { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public virtual FotoBinary Content { get; set; }
}
public class FotoBinary
{
public int Id { get; set; }
public virtual Foto Owner { get; set; }
public byte[] Value { get; set; }
}
這樣,您就可以在需要時查詢只是string
& int
單獨的二進制數據分開的數據,並渴望負載或延遲加載。下面是這兩個實體之間的關係流利的映射:
// Foto entity
HasRequired(principal => principal.Content)
.WithRequiredPrincipal(dependent => dependent.Owner)
.WillCascadeOnDelete(true);
// FotoBinary entity
HasRequired(dependent => dependent.Owner)
.WithRequiredDependent(principal => principal.Content)
.WillCascadeOnDelete(true);
當您使用類似於上面的一個映射,數據庫中的所有您Foto
和FotoBinary
行會共享同樣的主鍵(Id
) 。只要您知道其中一個的ID,就可以使用它查詢另一個的相應行(Owner
或Content
)。
最後,我會至少考慮不要將Lugar
實體傳遞給您的MVC操作。您可以改爲編寫一個ViewModel類,如LugarViewModel
。然後該類可以有一個HttpPostedFileBase
屬性in similar fashion to Karthik's answer。然後,您的控制器操作可以從視圖模型中獲取數據並使用它來填充實體。
如何調用'Create'? – 2013-02-19 12:30:00