仅更新其他字段后,图像文件设置为null

时间:2019-07-17 12:46:19

标签: c# asp.net-core entity-framework-core updating

在仅更新除图像以外的其他字段时,具有怪异的功能,其他字段(FirstNameLastName)成功更新,但是Image将其自身设置为null,但是当我根据其他字段(FirstNameLastName)选择它,它会成功更新。所以我想要的是当我不更新图像时将其保持原样,而无需将其自身设置为null。

这是我的New.cshtm文件,它同时处理创建和编辑数据:

<form asp-action="New" method="Post" asp-controller="Student" enctype="multipart/form-data">
    <div asp-validation-summary="All"></div>

    <input asp-for="Id" type="hidden"/>
    <input name="IsEditMode" id="IsEditMode" value="@ViewBag.IsEditMode" type="hidden"/>


    <div class="form-row">
        <label>Upload Photo</label>
        <input asp-for="ImageUrl" type="file" id="file"  name="file" class="form-control"/>

    </div>

    <div class="form-row">
        <div class="col">
            <label asp-for="FirstName"></label>
            <input asp-for="FirstName" class="form-control"/>
            <span asp-validation-for="FirstName" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="MiddleName"></label>
            <input asp-for="MiddleName" class="form-control"/>
            <span asp-validation-for="MiddleName" class="text-danger"></span>
        </div>
    </div>
</form>

然后这些是我的 controller Student.cs正在用来更新字段的方法:

public IActionResult New(Student student, string IsEditMode, IFormFile file)
        {

            if (!ModelState.IsValid)
            {
                ViewBag.IsEditMode = IsEditMode;
                return View(student);
            }

            try
            {

                if (IsEditMode.Equals("false"))
                {

                    _studentRepository.Create(student);
                     UploadFile(file, student.Id);
                    _toastNotification.AddSuccessToastMessage("Student has been created successfully.");

                }

                else
                {
                    _studentRepository.Edit(student);
                     UploadFile(file, student.Id);
                    _toastNotification.AddSuccessToastMessage("Student has been edited successfully.");

                }

                return RedirectToAction(nameof(Index));
            }
            catch (Exception e)
            {

                return RedirectToAction(nameof(Index));
            }

        }

        public IActionResult Edit(int id)
        {

            try
            {

                ViewBag.IsEditMode = "true";

                var student = _studentRepository.GetSingleStudent(id);

                return View("New", student);
            }
            catch (Exception ex)
            {
                return Content("Could not find Pet");
            }

        }

        public void UploadFile(IFormFile file, long studentId)
        {
            var fileName = file.FileName;
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images",fileName);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            var student = _studentRepository.GetSingleStudent(studentId);
            student.ImageUrl = fileName;
            _studentRepository.Edit(student);
        }

然后,这就是我在存储库中更新的方式:

然后在我的存储库中,这就是我更新字段“:

public void Edit(Student student)
        {
            var existingStudent = _context.Students

                .FirstOrDefault(s => s.Id == student.Id);

            if (existingStudent != null)
            {
                // updating student.

                _context.Entry(existingStudent).CurrentValues.SetValues(student);
                _context.Entry(existingStudent).State = EntityState.Modified;
          }
}

Index.cshtml,这是一个图像列表,其中包括名字和姓氏以及(动作按钮) EditDelete按钮:

<table class="table table-striped">
        <thead class="thead-dark">
        <tr>
            <td ><b>Student Picture</b></td>
            <td><b>FirstName</b></td>
            <td><b>LastName</b></td>
            <td colspan="2"> <b>Actions</b></td>
        </tr>
        </thead>
        <tbody>
        @foreach (var student in Model)
        {
            <tr>
                <td>@student.StudentRegNo</td>
                <td>
                    <div class="thumbnail">
                        <img src="/images/@student.ImageUrl" width="90" height="90"/>
                    </div>
                </td>
                <td>@student.FirstName</td>
                <td>@student.LastName</td>
                <d>
                    <td>
                        <a class="btn btn-warning" asp-action="Details" asp-controller="Student" asp-route-Id="@student.Id">Details</a>
                    </td>
                    <td>
                        <a class="btn btn-primary" asp-action="edit" asp-route-Id="@student.Id">Edit</a>
                    </td>
                    <td>
                        <a
                            class="btn btn-danger delete"
                            asp-route-Id="@student.Id"
                            asp-action="Delete">
                            Delete
                        </a>
                    </td>
                </d>
            </tr>
        }
        </tbody>
    </table>

编辑

这是根据@Raul解决方案的当前逻辑,但它不起作用:

if (student.ImageUrl != null)
                {
                    _context.Entry(existingStudent).CurrentValues.SetValues(student);
                    _context.Entry(existingStudent).State = EntityState.Modified;
                }

                else
                {
                    _context.Entry(existingStudent).Property(x => x.ImageUrl).IsModified = false; 
                    _context.Entry(existingStudent).CurrentValues.SetValues(student);
                    _context.Entry(existingStudent).State = EntityState.Modified;
                }

2 个答案:

答案 0 :(得分:1)

在您的Edit学生方法中,可以将ImageUrl IsModified的{​​{1}}设置为false,这不会更新数据库中的image字段:

Property

当然,您需要在此检查您的public void Edit(Student student) { var existingStudent = _context.Students.FirstOrDefault(s => s.Id == student.Id); if (existingStudent != null) { // updating student. _context.Student.Attach(existingStudent); _context.Entry(existingStudent).State = EntityState.Modified; _context.Entry(existingStudent).Property(x => x.ImageUrl).IsModified=false; _context.SaveChanges(); } } 逻辑。如果获得新图像,则将相应地更新模型。

编辑

您可以像这样合并if-else条件:

ImageUrl

答案 1 :(得分:1)

您可以分别考虑这两种情况。在不更新图像而更新字段时,文件为null,则需要将现有学生的ImageUrl关联到发布的学生。

        //...
        try
        {
            if (IsEditMode.Equals("false"))
            {
                _studentRepository.Create(student);
                UploadFile(file, student.Id);
                _toastNotification.AddSuccessToastMessage("Student has been created successfully.");

            }
            else
            {
                //edit mode
                if(file == null)//Updating fields without updating the image.
                {
                    var existingStudent = _context.Students.FirstOrDefault(s => s.Id == student.Id);

                    if (existingStudent != null)
                    {
                        // updating student with previousImageUrl
                        student.ImageUrl = existingStudent.ImageUrl;
                        _context.Entry(existingStudent).CurrentValues.SetValues(student);
                        _context.Entry(existingStudent).State = EntityState.Modified;
                        _context.SaveChanges();
                    }
                }
                else//Updating the fields and the image
                {
                    _studentRepository.Edit(student);
                    UploadFile(file, student.Id);
                }

                _toastNotification.AddSuccessToastMessage("Student has been edited successfully.");

            }

            return RedirectToAction(nameof(Index));
        }
        catch (Exception e)
        {
            return RedirectToAction(nameof(Index));
        }
    }

    public void UploadFile(IFormFile file, long studentId)
    {
        var fileName = file.FileName;
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName);

        using (var fileStream = new FileStream(path, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }

        var student = _studentRepository.GetSingleStudent(studentId);
        student.ImageUrl = fileName;
        _studentRepository.Edit(student);
    }

   public void Edit(Student student)
    {
        var existingStudent = _context.Students

            .FirstOrDefault(s => s.Id == student.Id);

        if (existingStudent != null)
        {
            // updating student.

            _context.Entry(existingStudent).CurrentValues.SetValues(student);
            _context.Entry(existingStudent).State = EntityState.Modified;
            _context.SaveChanges();
       }
    }