将项插入到UnitofWork存储库-对象未保存-ASP.Net MVC
本文关键字:对象 保存 -ASP MVC Net 插入 UnitofWork 存储 | 更新日期: 2023-09-27 18:05:36
我在提交一个图像对象和一个"KitchenItem"时,遇到了一个或多个特定对象的插入代码问题,该对象是从包含基本id和描述字符串的"Post"对象派生而来的。
我已经实现了ASP.Net教程中的通用存储库,这适用于网站的其他元素。
图像对象:
public class Image
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string AltText { get; set; }
[DataType(DataType.Html)]
public string Caption { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string ImageUrl { get; set; }
private DateTime? createdDate { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime CreatedDate
{
get { return createdDate ?? DateTime.UtcNow; }
set { createdDate = value; }
}
}
KitchenItem(我知道我正在用图像重复代码,我想将特定的图像附加到我的网站中的元素,而多次上传并没有实现我想要做的……尽管我对更干净的代码的建议持开放态度,但偏离主题(
public class KitchenItem:Post
{
public Image MainSlider { get; set; }
public Image MainSlider2 { get; set; }
public Image MainSlider3 { get; set; }
public Image MainSlider4 { get; set; }
public Image MainSlider5 { get; set; }
public Image SideImage1 { get; set; }
public Image SideImage2 { get; set; }
}
}
视图模型:
public class CreateProjectViewModel
{
public KitchenItem KitchenItem { get; set; }
public HttpPostedFileBase MainSlider1 { get; set; }
public HttpPostedFileBase MainSlider2 { get; set; }
public HttpPostedFileBase MainSlider3 { get; set; }
public HttpPostedFileBase MainSlider4 { get; set; }
public HttpPostedFileBase MainSlider5 { get; set; }
public HttpPostedFileBase SideImage { get; set; }
public HttpPostedFileBase SideImage2 { get; set; }
}
在控制器中创建功能:
public ActionResult Create( CreateProjectViewModel viewModel)
{
KitchenItem model = new KitchenItem();
model = viewModel.KitchenItem;
try
{
// handle image uploads manually
if(viewModel.MainSlider1!=null){
model.MainSlider = AddImage(viewModel.MainSlider1, model.MainSlider);
}
if(viewModel.MainSlider2!=null){
model.MainSlider2 = AddImage(viewModel.MainSlider2, model.MainSlider2);
}
if( viewModel.MainSlider3!=null){
model.MainSlider3 = AddImage(viewModel.MainSlider3, model.MainSlider3);
}
if(viewModel.MainSlider4!=null){
model.MainSlider4 = AddImage(viewModel.MainSlider4, model.MainSlider4);
}
if(viewModel.MainSlider5!=null){
model.MainSlider5 = AddImage(viewModel.MainSlider5, model.MainSlider5);
}
if(viewModel.SideImage!=null){
model.SideImage1 = AddImage(viewModel.SideImage, model.SideImage1);
}
if(viewModel.SideImage2!=null)
{
model.SideImage2 = AddImage(viewModel.SideImage2, model.SideImage2);
}
//Log date posted
model.PostedOn = DateTime.Now;
model.Category = unitofWork.CategoryRepository.GetByID(model.CategoryID);
//create post
unitofWork.KitchenItemRepository.Insert(model);
unitofWork.Save();
return RedirectToAction("Index");
}
catch (DataException dex )
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
ModelState.AddModelError("", "Unable to save changes.Image files not saved and Kitchen Item not Updated");
}
PopulateCategoriesDropDownList();
return RedirectToAction("Index");
}
添加图像功能:
public Image AddImage(HttpPostedFileBase imageToSave, Image modelImage)
{
Image img = new Image();
img = modelImage;
img.ImageUrl=SaveUploadedFile(imageToSave, img.Id);
unitofWork.ImagesRepository.Insert(img);
return img;
}
我已经使用断点跟踪了操作,AddImage函数起作用,并成功地将图像传递回Create((-类似地,Create((中的模型显示,它包含所有预期的内容,直到工作单元。kitchenItem.Insert(模型(;
我的一些想法是,这与函数的关系元素有关,所有图像id的初始值都是0……尽管我认为数据库插入会处理这个问题?
通用存储库:
public class GenericRepository<TEntity> where TEntity : class
{
internal GlenlithContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(GlenlithContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
上下文:
public class Context : DbContext
{
public Context()
: base("Context")
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<KitchenItem> KitchenItems { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Post>().HasOptional(c=>c.Category);
modelBuilder.Entity<Post>().HasOptional(c => c.Tags);
modelBuilder.Entity<KitchenItem>()
.Map(m =>
m.ToTable("KitchenItems"));
modelBuilder.Entity<KitchenItem>().HasOptional(c => c.Category);
modelBuilder.Entity<KitchenItem>().HasOptional(c => c.Tags);
modelBuilder.Entity<KitchenItem>().HasMany(c => c.MainSliderPath);
}
}
视图:
@model Glenlith.ViewModels.CreateProjectViewModel
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"> </script>
<style>
.imagePreview {
width: 870px;
height: 420px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
.sideImagePreview {
width: 270px;
height: 200px;
background-position: center center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
</style>
<div class=" row">
<h2>Create Kitchen Project</h2>
</div>
<div class=" row">
@using (Html.BeginForm("Create", "KitchenItems", FormMethod.Post, new { EncType = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class=" row">
<div class=" col-md-12">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Main Slider 1</a></li>
<li><a href="#tabs-2">Main Slider 2</a></li>
<li><a href="#tabs-3">Main Slider 3</a></li>
<li><a href="#tabs-4">Main Slider 4</a></li>
<li><a href="#tabs-5">Main Slider 5</a></li>
<li><a href="#tabs-6">Side Image 1</a></li>
<li><a href="#tabs-7">Side Image 2</a></li>
</ul>
<div id="tabs-1">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview" class=" imagePreview"></div>
Images for the Main Slider should be saved as 870px by 420px
<div class="form-group">
@Html.LabelFor(model => model.MainSlider1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.MainSlider1, new { type = "file", id = "uploadFile" })
@Html.ValidationMessageFor(model => model.MainSlider1,"", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-2">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider2.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider2.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider2.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider2.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider2.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview2" class=" imagePreview"></div>
Images for the Main Slider should be saved as 870px by 420px
<div class="form-group">
@Html.LabelFor(model => model.MainSlider2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.MainSlider2, new { type = "file", id = "uploadFile2" })
@Html.ValidationMessageFor(model => model.MainSlider2, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-3">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider3.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider3.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider3.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider3.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider3.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider3.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview3" class=" imagePreview"></div>
Images for the Main Slider should be saved as 870px by 420px
<div class="form-group">
@Html.LabelFor(model => model.MainSlider3, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.MainSlider3, new { type = "file", id = "uploadFile3" })
@Html.ValidationMessageFor(model => model.MainSlider3, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-4">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider4.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider4.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider4.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider4.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider4.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider4.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview4" class=" imagePreview"></div>
Images for the Main Slider should be saved as 870px by 420px
<div class="form-group">
@Html.LabelFor(model => model.MainSlider4, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.MainSlider4, new { type = "file", id = "uploadFile4" })
@Html.ValidationMessageFor(model => model.MainSlider4, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-5">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider5.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider5.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider5.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.MainSlider5.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.MainSlider5.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.MainSlider5.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview5" class=" imagePreview"></div>
Images for the Main Slider should be saved as 870px by 420px
<div class="form-group">
@Html.LabelFor(model => model.MainSlider5, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.MainSlider5, new { type = "file", id = "uploadFile5" })
@Html.ValidationMessageFor(model => model.MainSlider5, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-6">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.SideImage1.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.SideImage1.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.SideImage1.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.SideImage1.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.SideImage1.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.SideImage1.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview6" class=" imagePreview"></div>
Side Images should be saved as 270px by 200px
<div class="form-group">
@Html.LabelFor(model => model.SideImage, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.SideImage, new { type = "file", id = "uploadFile6" })
@Html.ValidationMessageFor(model => model.SideImage, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-7">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.SideImage2.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.SideImage2.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.SideImage2.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.SideImage2.AltText, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.SideImage2.AltText, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.SideImage2.AltText, "", new { @class = "text-danger" })
</div>
</div>
<div id="imagePreview7" class=" imagePreview"></div>
Side Images should be saved as 270px by 200px
<div class="form-group">
@Html.LabelFor(model => model.SideImage2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.SideImage2, new { type = "file", id = "uploadFile7" })
@Html.ValidationMessageFor(model => model.SideImage2, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<div class=" col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.Title, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.ShortDescription, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.ShortDescription, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.ShortDescription, "", new { @class = "text-danger" })
</div>
</div>
<div class=" col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.Description, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.Meta, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.Meta, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.Meta, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.UrlSlug, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
@Html.EditorFor(model => model.KitchenItem.UrlSlug, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.KitchenItem.UrlSlug, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.KitchenItem.Published, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.KitchenItem.Published)
@Html.ValidationMessageFor(model => model.KitchenItem.Published, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.KitchenItem.CategoryID, "Category")
</div>
<div class="editor-field">
@Html.DropDownList("CategoryID", String.Empty)
@Html.ValidationMessageFor(model => model.KitchenItem.CategoryID)
</div>
</div>
<div class=" row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</div>
<style type="text/css">
.dz-max-files-reached {
background-color: red;
}
</style>
@section scripts{
<script type="text/javascript">
//File Upload response from the server
Dropzone.options.dropzoneForm = {
maxFiles: 10,
init: function () {
this.on("maxfilesexceeded", function (data) {
var res = eval('(' + data.xhr.responseText + ')');
});
}
};
</script>
<script>
$(function () {
$("#tabs").tabs();
});
</script>
<script src="~/js/sliderUpload.js"></script>
}
如果有任何帮助,我将不胜感激。我对MVC相对较新,热衷于构建干净的代码,我知道了解映射和处理数据库是我最大的障碍。
public Image AddImage(HttpPostedFileBase imageToSave, Image modelImage)
{
Image img = new Image();
img = modelImage;
img.ImageUrl=SaveUploadedFile(imageToSave, img.Id);
unitofWork.ImagesRepository.Insert(img);
unitOfWork.SaveChanges(); // you didn't save the change.
return img;
}
您没有保存更改,因此工作单元将不会保留插入操作。检查上面的代码。在工作单元中,您应该有Save((或SaveChanges((方法来包装DbContext.SaveChanges(。