如何使用 Entity Framework 核心先插入子数据,然后插入父数据和子插入标识

How to insert child data first and then parent data and child inserted identity using Entity Framework Core

我有一个要求,我需要先在子 table 中插入数据,然后在其父项中插入数据,然后子项将记录标识插入到父项 table 中,这就是我在更新现有数据时所做的记录。让我们看看请求正文:

{
    "StudentId": 111001,
    "StudentName": "Gaurav Singh",
    "Address": 
    [
        {
            "AddressId" : 223344,
            "AddressType": 1,
            "StudentId" : 111001,
            "AddressLine1": "Noida Sec 15",
            "City": "Noida",
            "State": "U.P.",
            "Country": "India",
            "PhoneId":311386
            "PhoneNumber": {
                "PhoneId": 311386,
                "PhoneNumber": "123456789"
            }
        },
        { // this my new entry in database which is not getting inserted.
            "AddressId" : null,
            "AddressType": 2,
            "StudentId" : 111001,
            "AddressLine1": "Noida Sec 18",
            "City": "Noida",
            "State": "U.P.",
            "Country": "India",
            "PhoneId":0
            "PhoneNumber": {
                "PhoneId": NULL,
                "PhoneNumber": "2233445566"
            }
        }
    ]
}

现在在我的代码中,我正在尝试使用以下代码,但它在更新现有数据时不起作用,但对于整个新记录,它工作正常。

foreach (var _adressData in data.Addresses.ToList())
{
    var _address = _context.Address
                           .Where(p => p.AddressId == _adressData.AddressId)
                           .FirstOrDefault();

    if (_address != null)
    {
        _context.Entry(_address).CurrentValues.SetValues(_adressData);
    }
    else
    {
        var _adr = new Address
        {
            AddressId = null,
            AddressType = 2,
            StudentId = 111001,
            AddressLine1 = "Noida Sec 18",
            City = "Noida",
            State = "U.P.",
            Country = "India",
            PhoneNumber = new PhoneNumberEntity{
                PhoneId = NULL,
                PhoneNumber = "2233445566"
            }
        };

        currentData.Address.Add(_adr);
    }
}

await _context.SaveChangesAsync();
return currentData;

有人有什么建议吗?

课程是 -

public class student {
    public int StudentId {get;set;}
    public string StudentName {get;set;}
    public ICollection<AddressEntity> Addresses {get;set;}}

public class AddressEntity {
    public int StudentId {get;set;}
    public int AddressType {get;set;}
    public int PhoneId {get;set;}
    public string AddressLine1 {get;set;}
    public string City {get;set;}
    public string State {get;set;}
    public string Country {get;set;}
    public PhoneEntity PhoneNumber {get;set;} }

public class PhoneEntity {
    public int PhoneId {get;set;}
    public string PhoneNumber {get;set;} }

谢谢

问题是您的 PhoneEntity PhoneNumber 属性 是虚拟的。为了给你真实的代码,我需要你的真实代码。现在我只能建议:


if (_address != null)
    {

       var phone = _context.Phone
                           .Where(p => p.PhoneId == _adressData.PhoneId)
                           .FirstOrDefault();
  if (phone != null)   _context.Entry(Phone).CurrentValues.SetValues(_adressData.Phone);
     
          _adressData.Phone=null;
       
         _context.Entry(_address).CurrentValues.SetValues(_adressData);
       
    }
public class student {
    public int StudentId {get;set;}
    public string StudentName {get;set;}
    public ICollection<AddressEntity> Addresses }

首先,对于学生 class,尝试为地址 属性.

添加 getset 方法
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public ICollection<AddressEntity> Addresses { get; set; }
}

其次,在EditPost方法中,尝试参考以下样例更新模型:

   [HttpPost]
    public IActionResult Edit(Student student)
    { 
        //based on the student's StudentId property to find the existing item from the database.
        var existStudent = _context.Students
            .Include(c=>c.Addresses).ThenInclude(c=>c.PhoneNumber)
            .Where(c => c.StudentId == student.StudentId).FirstOrDefault();

        //define a list to store the student's address.
        var address = new List<AddressEntity>();

        if(existStudent != null)
        {
            //loop through the address list from the student (post parameters).
            foreach (var _adressData in student.Addresses.ToList())
            {
                //check if the address is exist or not.
                var _address = _context.Addresses
                                       .Where(p => p.AddressId == _adressData.AddressId)
                                       .FirstOrDefault();

                if (_address != null)
                {
                    //update the exist address.
                    _context.Entry(_address).CurrentValues.SetValues(_adressData); //update the existing address.
                    //add the existing address to the list.
                    address.Add(_address);
                }
                else
                {
                   //add new address object to the list.
                   address.Add(_adressData);
                }
            }
            existStudent.Addresses = address; //set address for the student.
        }
        _context.SaveChanges(); //call the SaveChange method 

        var latestdata = _context.Students.ToList();

        return View();
    }

结果是这样的(编辑前已有学生有一个地址,修改后有两个地址):