MVC控制器-使用外键在数据库中存储图像
本文关键字:数据库 存储 图像 控制器 MVC | 更新日期: 2023-09-27 18:18:53
我目前有两个表,其中一个与外键连接:
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
使用实体数据模型向导生成模型。
我试图在表中保存图像。图片>用户号为6的图片内容
h2控制器 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);
}
Razor View (Index)
@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 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显示。
Thank you
也许我错过了一些东西,但我看不到你在逻辑中设置user_no的位置。无论如何,您的user_no和数据库中的现有用户之间似乎没有匹配来满足外键。确保将image的user_no设置为用户表中已有的user_no值。
你可以在Add和Save调用之前硬编码测试:
pic.user_no = 6;
db.tbl_picture.Add(pic);
db.SaveChanges();
但是最终的解决方案应该从当前用户或html表单中获得它。比如:
pic.user_no = AuthenticationHelper.CurrentUser.UserID;
在这两种情况下,user_no = 6的用户行必须在之前的表中存在。
顺便说一句。我真的不喜欢你使用的命名约定……: P