2013-02-19 37 views
0

裏面我Lugar類我有這樣的:如何處理圖像在Asp.net的mvc 4工作,實體框架

public virtual Foto FotosLugar { get; set; } 

我有這樣的定義:

public class Foto 
{ 
    [Column(TypeName = "image")] 
    public byte[] Binary { get; set; } 
} 

在我LugarController我已嘗試:

public ActionResult Create(Lugar lugar, HttpPostedFileBase FotosLugar) 

我試圖做一些轉換,但它也沒有工作...

我想一個Image存儲類Lugar ....

+0

如何調用'Create'? – 2013-02-19 12:30:00

回答

0

我不知道這有什麼關係EF內。看起來你還沒有到達那裏。

你所說的是,你不能接收裏面的一個文件創建控制器行動,對不對?

您至少有兩種選擇:

  • 有一個參數(HttpPostedFile/IEnumerable的),並從模型中分別獲得圖像
  • 或者你可以簡單地訪問Request.Files行動在你的控制器的任何地方,你會得到一個上傳文件的集合,然後添加到你的Lugar類。有沒有需要有額外的FotosLugar參數
1

試試這個:

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實體類中。

一對夫婦的其他注意事項:這也許不是一個壞主意,還存放了ContentLengthContentType,並在您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); 

當您使用類似於上面的一個映射,數據庫中的所有您FotoFotoBinary行會共享同樣的主鍵(Id) 。只要您知道其中一個的ID,就可以使用它查詢另一個的相應行(OwnerContent)。

最後,我會至少考慮不要將Lugar實體傳遞給您的MVC操作。您可以改爲編寫一個ViewModel類,如LugarViewModel。然後該類可以有一個HttpPostedFileBase屬性in similar fashion to Karthik's answer。然後,您的控制器操作可以從視圖模型中獲取數據並使用它來填充實體。

+0

對不起,但你的控制器代碼不工作..... 行var foto = new Foto {Binary = content}; 它說它沒有Binary的定義,所以我嘗試了內容=內容,但沒有工作,或者.....我嘗試了很多更改,但沒有任何工作......我試圖先創建一個FotoBInary ..... 我還在學習asp.net MVC,如果你能幫助我,我會讚賞很多....你已經幫了很多,但現在我有點失落..... – 2013-02-20 00:49:14

+0

我會深入瞭解一下在這個一對一的明天... 我會看到如何解決這個問題 – 2013-02-20 03:51:00

+0

我基於很多關於原始問題中示例類的代碼。如果您遇到編譯器錯誤,請確保您的原始問題中包含名爲'Binary'的屬性的'Foto'類。 – danludwig 2013-02-20 12:34:45

0

OK,下面是它我採取:像您最初指定