【发布时间】:2016-01-22 19:12:30
【问题描述】:
我目前有两张表,其中一张用外键连接:
dbo.tbl_user dbo.tbl_picture
-------- -----------
PK user_no PK picture_id
user_username picture_content
user_password FK user_no (relational to tbl.user PK)
user_emailaddress
已使用实体数据模型向导生成模型。
我试图将图像保存在 tbl.picture > 图片内容中,其中 user no 的值为 6 。
控制器
UserDBContext db = new UserDBContext(); (Entity Framework)
public ActionResult Create(tbl_picture pic , HttpPostedFileBase file)
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
pic.picture_content = file.FileName;
}
db.tbl_picture.Add(pic);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pic);
}
剃刀视图(索引)
@Html.ActionLink("Create New", "Create")
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.picture_content)
}
@using (Html.BeginForm("Create", "Home", null, FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.picture_id)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
}
我收到的问题是: UserDBContext.tbl_picture 中的实体参与“FK_tbl_picture_emp_no”关系。找到 0 个相关的“tbl_user”,预计有 1 个“tbl_user”。
我正在尝试根据特定的 user_no 在同一个视图中保存和上传图像,因此将来当该用户登录时,将根据他的 user_no 显示个人资料图片。
谢谢
【问题讨论】:
-
如果您需要将图像保存在数据库中,那么您必须将图像保存为缓冲区字节数组。但我建议将图像保存在服务器中并将唯一的图像名称保存在数据库审查stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0
-
谢谢,虽然这并没有直接回答我的问题。
标签: c# entity-framework model-view-controller controller