问题描述
我有一个要求,我需要先在子表中插入数据,然后在其父表中插入数据,然后在父表中插入记录标识,这就是我在更新现有记录时正在做的事情。让我们看看请求正文:
{
"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,"AddressLine1": "Noida Sec 18","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;} }
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)