首页 > 解决方案 > 如何使用 Entity Framework Core 先插入子数据,然后插入父数据和子插入身份

问题描述

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

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

谢谢

标签: entity-frameworkasp.net-coresavechanges

解决方案


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

首先,对于 Student 类,尝试为 Addresses 属性添加getset方法。

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

其次,在 Edit Post 方法中,尝试参考以下示例来更新模型:

   [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();
    }

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

在此处输入图像描述


推荐阅读