![](/img/trans.png)
[英]How do I add ONLY specific DB Entity Sets to the ViewData in ASP.NET MVC 4 Entity Framework?
[英]How do I work with Images in Asp.net Mvc 4, Entity Framework
在我的班级Lugar
我有这个:
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
类中。
尝试这个:
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实体类中。
其他一些注意事项:在Foto
实体上还存储ContentLength
, ContentType
和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动作中。 您可以改为LugarViewModel
一个ViewModel类,例如LugarViewModel
。 然后,该类可以具有与Karthik的answer类似的方式的HttpPostedFileBase
属性。 然后,您的控制器动作可以从视图模型中获取数据,并使用其填充Lugar
实体。
我不确定这是否与EF有关。 看来您还没到那儿。
您的意思是您无法在控制器的Create操作中接收文件,对吗?
您至少有两个选择:
好,这是我的看法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.