簡體   English   中英

將項目插入到UnitofWork存儲庫-不保存對象-ASP.Net MVC

[英]Inserting items to UnitofWork Repository - objects not saving - ASP.Net MVC

我要提交圖像對象,然后從包含基本ID,描述字符串的“ Post”對象派生的“ KitchenItem”時,遇到特定對象或技術對象的插入代碼問題。

我已經從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()中的模型顯示,該圖像包含直到unitofwork.kitchenItem.Insert(model );

我有一些想法是,它與函數的關系元素有關,所有圖像ID的初始值都為0 ...盡管我會假設db insert會處理這個問題?

通用存儲庫:

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;
    }

您沒有保存更改,因此,工作單元將不會保留插入操作。 檢查上面的代碼。 在工作單元中,您應該具有包裝DbContext.SaveChanges()的Save()或SaveChanges()方法,以保留您的更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM