0
Homam created
Hi,
I am trying to save two records together (parent / child) in one transaction. However, the second record foreign key value is not getting the generated Id of parent and has a negative value.
My code:
public async Task<FieldDto> Create(Guid listId, CreateFieldInput input)
{
await CheckParentIfExists(listId);
await CheckIfAlreadyExists(listId, input.Name);
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
var list = _listRepository.Get(listId);
var record = ObjectMapper.Map<Field>(input);
record.ListId = listId;
var insertedRecord = await _repository.InsertAsync(record);
if (input.LinkedListId.HasValue)
{
// If a link is created between two entities,
// a new field is automatically added to the other entity
Field slaveField = new Field
{
ListId = input.LinkedListId.Value,
MasterFieldId = insertedRecord.Id,
DataType = (int)FieldDataType.LinkList,
IsPrimary = false,
IsVisible = true,
IsRequired = false,
Name = list.Name,
Description = list.Name,
};
// HERE THE insertedRecord.Id, IS A WRONG NEGATIVE VALUE IN THE DATABASE :roll:
await _repository.InsertAsync(slaveField);
}
await uow.CompleteAsync();
return ObjectMapper.Map<FieldDto>(insertedRecord);
}
}
How can I fix it?
1 Answer(s)
-
0
You need a navigation property:
MasterFieldId = insertedRecord.Id, // Doesn't work in a single transaction MasterField = insertedRecord, // Works