简体   繁体   English

我无法使用Entity Framework Core更新/编辑一对一关系

[英]I can't update/edit One to one relationship with Entity Framework Core

All CRUD operations are working except updating/editing. 除更新/编辑外,所有CRUD操作均有效。 I am using Pomelo since I am using Mysql. 我正在使用Pomelo,因为我正在使用Mysql。 For the issue am facing, am using the same create form to edit the data but it throws an exception when I try editing. 对于面临的问题,我正在使用相同的创建表单来编辑数据,但是当我尝试编辑时会引发异常。

This is the exception: 这是例外:

fail: Microsoft.EntityFrameworkCore.Update[10000] 失败:Microsoft.EntityFrameworkCore.Update [10000]
An exception occurred in the database while saving changes for context type 'ICFERApp.Data.ApplicationDbContext'. 保存上下文类型为“ ICFERApp.Data.ApplicationDbContext”的更改时,数据库中发生了异常。

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。 See the inner exception for details. 有关详细信息,请参见内部异常。

MySql.Data.MySqlClient.MySqlException: Duplicate entry '3' for key 'IX_Education_StudentId' MySql.Data.MySqlClient.MySqlException:密钥“ IX_Education_StudentId”的条目“ 3”重复

MySql.Data.MySqlClient.MySqlException: Duplicate entry '3' for key 'IX_Education_StudentId' MySql.Data.MySqlClient.MySqlException:密钥“ IX_Education_StudentId”的条目“ 3”重复

at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in C:\\projects\\mysqlconnector\\src\\MySqlConnector\\Core\\ResultSet.cs:line 43 在C:\\ projects \\ mysqlconnector \\ src \\ MySqlConnector \\ Core \\ ResultSet.cs:line 43中的MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior)
--- End of inner exception stack trace --- ---内部异常堆栈跟踪的结尾---
at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in C:\\projects\\mysqlconnector\\src\\MySqlConnector\\MySql.Data.MySqlClient\\MySqlDataReader.cs:line 81 在C:\\ projects \\ mysqlconnector \\ src \\ MySqlConnector \\ MySql.Data.MySqlClient \\ MySqlDataReader.cs:line 81中的MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet)
at MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) in C:\\projects\\mysqlconnector\\src\\MySqlConnector\\MySql.Data.MySqlClient\\MySqlDataReader.cs:line 307 在C:\\ projects \\ mysqlconnector \\ src \\ MySqlConnector \\ MySql.Data.MySqlClient \\ MySqlDataReader.cs:line 307的MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior)

These are my model classes: 这些是我的模型类:

public class Student
{
        [Key]
        public long Id { get; set; }
        [Display(Name="First Name")]
        public string FirstName { get; set; }
        [Display(Name="Middle Name")]
        public string MiddleName { get; set; }
        [Display(Name="Last Name")]
        public string LastName { get; set; }
        [Display(Name="Nationality")]
        public string Nationality { get; set; }
        [Display(Name="Gender")]
        public string Gender { get; set; }
        [Display(Name="Religion")]
        public string Religion { get; set; }
        [Display(Name="Medical Condition")]
        public string MedicalCondition { get; set; }
        [Display(Name="Deceased")]
        public string Deceased { get; set; }
        [Display(Name="Home Address")]
        public string HomeAddress { get; set; }
        [Display(Name="Country Of Residence")]
        public string CountryOfResidence { get; set; }
        [Display(Name="City")]
        public string City { get; set; }
        [Display(Name="Date Of Birth")]
        public DateTime DateOfBirth { get; set; }
        public int Age { get; set; }

        public virtual Parents Parents { get; set; }
        public virtual Education Education { get; set; }
}

public class Parents
{
        public long Id { get; set; }
        [Display(Name="Religion Of Deceased Father")]
        public string ReligionOfDeceasedFather { get; set; }
        [Display(Name="Religion Of Deceased Mother")]
        public string ReligionOfDeceasedMother { get; set; }
        [Display(Name="Date Of Demise Father")]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime DateOfDemiseOfFather { get; set; }
        [Display(Name="Date Of Demise Mother")]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime DateOfDemiseOfMother { get; set; }
        [Display(Name="Names of Mother")]
        public string NamesOfMother { get; set; }
        [Display(Name="Names of Father")]
        public string NamesOfFather { get; set; }
        [Display(Name="Religion of Mother")]
        public string ReligionOfMother { get; set; }
        [Display(Name="Marital Status of Mother")]
        public string MaritalStatusOfMother { get; set; }
        [Display(Name="Occupation of Mother")]
        public string OccupationOfMother { get; set; }
        [Display(Name="Monthly Income")]
        public double MonthlyIncome { get; set; }
        public virtual Student Student { get; set; }

        public long? StudentId { get; set; }
}

public class Education
{
    public long Id { get; set; }
    [Display(Name="Education Level")]
    public string EducationLevel { get; set; }
    [Display(Name="School")]
    public string School { get; set; }
    [Display(Name="Address of School")]
    public string AddressOfSchool { get; set; }
    [Display(Name="Head Teacher")]
    public string HeadTeacher { get; set; }
    [Display(Name="Telephone")]
    public string Telephone { get; set; }
    public  virtual Student Student { get; set; }

    public long? StudentId { get; set; }
}

My question would be why can't I be able to update automatically with the Entity Framework Core? 我的问题是为什么我不能使用Entity Framework Core自动更新?

These are the methods responsible for editing in my Controller class : 这些是负责在我的Controller类中进行编辑的方法:

[HttpPost]
public IActionResult New(Student student, string IsEditMode)
{
     if (!ModelState.IsValid)
     {
         ViewBag.IsEditMode = IsEditMode;
         return View(student);
     }

     try
     {
         if (IsEditMode.Equals("false"))
         {
              _studentRepository.Create(student);
         }
         else
         {
             _studentRepository.Edit(student);
         }

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

Then, in my Repository class, this is the Edit method: 然后,在我的Repository类中,这是Edit方法:

public void Edit(Student student)
{
    _context.Students.Update(student);
    _context.SaveChanges();
} 

I will be very grateful with help regarding this blocker. 我将非常感谢您提供有关此阻止程序的帮助。 Thanks. 谢谢。

EDIT 编辑

This is my form which handles both Creating and Editing. 这是我的表格,处理创建和编辑。

@model Student

<form asp-action="New" method="Post" asp-controller="Student">
    <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">
        <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>
    <div class="form-row">
        <div class="col">
            <label asp-for="LastName"></label>
            <input asp-for="LastName" class="form-control"/>
            <span asp-validation-for="LastName" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Nationality"></label>
            <input asp-for="Nationality" class="form-control"/>
            <span asp-validation-for="Nationality" class="text-danger"></span>
        </div>
    </div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Gender"></label>
            <input asp-for="Gender" class="form-control"/>
            <span asp-validation-for="Gender" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Religion"></label>
            <input asp-for="Religion" class="form-control"/>
            <span asp-validation-for="Religion" class="text-danger"></span>
        </div>
    </div>

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

    <div class="form-row">
        <div class="col">
            <label asp-for="HomeAddress"></label>
            <input asp-for="HomeAddress" class="form-control"/>
            <span asp-validation-for="HomeAddress" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="CountryOfResidence"></label>
            <input asp-for="CountryOfResidence" class="form-control"/>
            <span asp-validation-for="CountryOfResidence" class="text-danger"></span>
        </div>
    </div>
<div class="form-row">
    <div class="col">
        <label asp-for="City"></label>
        <input asp-for="City" class="form-control"/>
        <span asp-validation-for="City" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="DateOfBirth"></label>
        <input asp-for="DateOfBirth" class="form-control"/>
        <span asp-validation-for="DateOfBirth" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Parents.ReligionOfDeceasedFather"></label>
        <input asp-for="Parents.ReligionOfDeceasedFather" class="form-control"/>
        <span asp-validation-for="Parents.ReligionOfDeceasedFather" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Parents.ReligionOfDeceasedMother"></label>
        <input asp-for="Parents.ReligionOfDeceasedMother" class="form-control"/>
        <span asp-validation-for="Parents.ReligionOfDeceasedMother" class="text-danger"></span>
    </div>
</div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Parents.DateOfDemiseOfFather"></label>
            <input asp-for="Parents.DateOfDemiseOfFather" class="form-control"/>
            <span asp-validation-for="Parents.DateOfDemiseOfFather" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Parents.DateOfDemiseOfMother"></label>
            <input asp-for="Parents.DateOfDemiseOfMother" class="form-control"/>
            <span asp-validation-for="Parents.DateOfDemiseOfMother" class="text-danger"></span>
        </div>
    </div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Parents.NamesOfMother"></label>
            <input asp-for="Parents.NamesOfMother" class="form-control"/>
            <span asp-validation-for="Parents.NamesOfMother" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Parents.NamesOfFather"></label>
            <input asp-for="Parents.NamesOfFather" class="form-control"/>
            <span asp-validation-for="Parents.NamesOfFather" class="text-danger"></span>
        </div>
    </div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Parents.ReligionOfMother"></label>
            <input asp-for="Parents.ReligionOfMother" class="form-control"/>
            <span asp-validation-for="Parents.ReligionOfMother" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Parents.MaritalStatusOfMother"></label>
            <input asp-for="Parents.MaritalStatusOfMother" class="form-control"/>
            <span asp-validation-for="Parents.MaritalStatusOfMother" class="text-danger"></span>
        </div>
    </div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Parents.OccupationOfMother"></label>
            <input asp-for="Parents.OccupationOfMother" class="form-control"/>
            <span asp-validation-for="Parents.OccupationOfMother" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Parents.MonthlyIncome"></label>
            <input asp-for="Parents.MonthlyIncome" class="form-control"/>
            <span asp-validation-for="Parents.MonthlyIncome" class="text-danger"></span>
        </div>
    </div>
<div class="form-row">
    <div class="col">
        <label asp-for="Guardian.FirstName"></label>
        <input asp-for="Guardian.FirstName" class="form-control"/>
        <span asp-validation-for="Guardian.FirstName" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Guardian.MiddleName"></label>
        <input asp-for="Guardian.MiddleName" class="form-control"/>
        <span asp-validation-for="Guardian.MiddleName" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Guardian.LastName"></label>
        <input asp-for="Guardian.LastName" class="form-control"/>
        <span asp-validation-for="LastName" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Guardian.RelationshipToOrphan"></label>
        <input asp-for="Guardian.RelationshipToOrphan" class="form-control"/>
        <span asp-validation-for="Guardian.RelationshipToOrphan" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Guardian.Occupation"></label>
        <input asp-for="Guardian.Occupation" class="form-control"/>
        <span asp-validation-for="Guardian.Occupation" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Guardian.MonthlyIncome"></label>
        <input asp-for="Guardian.MonthlyIncome" class="form-control"/>
        <span asp-validation-for="Guardian.MonthlyIncome" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Guardian.EmployersName"></label>
        <input asp-for="Guardian.EmployersName" class="form-control"/>
        <span asp-validation-for="Guardian.EmployersName" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Guardian.WorkAddress"></label>
        <input asp-for="Guardian.WorkAddress" class="form-control"/>
        <span asp-validation-for="Guardian.WorkAddress" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Guardian.MobileNo"></label>
        <input asp-for="Guardian.MobileNo" class="form-control"/>
        <span asp-validation-for="Guardian.MobileNo" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Guardian.PhysicalLocation"></label>
        <input asp-for="Guardian.PhysicalLocation" class="form-control"/>
        <span asp-validation-for="Guardian.PhysicalLocation" class="text-danger"></span>
    </div>
</div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Guardian.Comments"></label>
            <input asp-for="Guardian.Comments" class="form-control"/>
            <span asp-validation-for="Guardian.Comments" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Education.EducationLevel"></label>
            <input asp-for="Education.EducationLevel" class="form-control"/>
            <span asp-validation-for="Education.EducationLevel" class="text-danger"></span>
        </div>
    </div>
<div class="form-row">
    <div class="col">
        <label asp-for="Education.School"></label>
        <input asp-for="Education.School" class="form-control"/>
        <span asp-validation-for="Education.School" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Education.AddressOfSchool"></label>
        <input asp-for="Education.AddressOfSchool" class="form-control"/>
        <span asp-validation-for="Education.AddressOfSchool" class="text-danger"></span>
    </div>
</div>
<div class="form-row">
    <div class="col">
        <label asp-for="Education.HeadTeacher"></label>
        <input asp-for="Education.HeadTeacher" class="form-control"/>
        <span asp-validation-for="Education.HeadTeacher" class="text-danger"></span>
    </div>
    <div class="col">
        <label asp-for="Education.Telephone"></label>
        <input asp-for="Education.Telephone" class="form-control"/>
        <span asp-validation-for="Education.Telephone" class="text-danger"></span>
    </div>
</div>
    <div class="form-row">
        <div class="col">
            <label asp-for="Siblings.NumberOfBrothers"></label>
            <input asp-for="Siblings.NumberOfBrothers" class="form-control"/>
            <span asp-validation-for="Siblings.NumberOfBrothers" class="text-danger"></span>
        </div>
        <div class="col">
            <label asp-for="Siblings.NumberOfSisters"></label>
            <input asp-for="Siblings.NumberOfSisters" class="form-control"/>
            <span asp-validation-for="Siblings.NumberOfSisters" class="text-danger"></span>
        </div>
    </div>

<div class="form-group">
    <input asp-for="FirstName" type="submit" value="Save Student" class="btn btn-primary"/>
</div>

</form>

This is how you can update all the tables 这是您可以更新所有表的方式

public void Edit(Student student)
{
    var existingStudent = _context.Students.FirstOrDefault(s => s.Id == student.Id);
    if (existingStudent != null)
    {
        //do the update to the database             
        _context.Entry(existingStudent).CurrentValues.SetValues(student);
        _context.Entry(existingStudent).State = System.Data.Entity.EntityState.Modified;

        //then update the parent this way
        //first get the particular parent for this student
        var parent = _context.Parents.FirstOrDefault(m => m.StudentId == existingStudent.Id);

        _context.Entry(parent).CurrentValues.SetValues(student.Parents);
        _context.Entry(parent).State = System.Data.Entity.EntityState.Modified;

        //do the same for Educations
    }
    _context.SaveChanges();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM