试试这个:
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