У меня есть требование, когда мне нужно сначала вставить данные в дочернюю таблицу, затем в ее родительскую, а затем дочернюю вставленную запись в родительскую таблицу, и это то, что я делаю при обновлении существующей записи. давайте посмотрим на тело запроса:
{
"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;} }
Спасибо