I have an entity like this:
public class Notification
{
public int Id { get; set; }
public bool IsReminderActive { get; set; }
public bool IsInvitationActive { get; set; }
public int ContractId { get; set; }
public bool IsActive { get; set; }
}
And if I want to update a entry or create a new one I'm trying something like this:
public async Task<bool> Post(Notification notificationEmail)
{
try
{
if (!_context.Notification.Any(x => x.ContractId == notificationEmail.ContractId))
{
_logger.LogInformation($"Creating new Notification for contract {notificationEmailType.ContractId}");
_context.Notification.Add(notificationEmail);
}
else
{
var update = _context.Notification.First(x => x.ContractId == notificationEmail.ContractId);
update.IsInvitationActive = notificationEmail.IsInvitationActive;
update.IsReminderActive = notificationEmail.IsReminderActive;
_logger.LogInformation($"Updating Notification for contract {notificationEmail.ContractId}");
_context.Notification.Update(update);
}
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError("Error trying to create/update Notification", ex);
return false;
}
return true;
}
I did the update part like that because if I try to update the entry with the notificationEmail variable, I had an error of duplicate key for ContractId.
SqlException: Cannot insert duplicate key row in object 'dbo.Notification' with unique index 'IX_Notification_ContractId'. The duplicate key value is (4).
There is a better way of writing the update code?
CodePudding user response:
First of all you should move the Update
code on a PUT
or a PATCH
Request, then you don't need to pass the id to the post when you create a new record
CodePudding user response:
Yes, you don't need to call Update()
because you already have a tracked instance when you use _context.Notification.First
.
Just attempt to get a tracked instance initially then update it if found.
public async Task<bool> Post(Notification notificationEmail)
{
try
{
var notification = _context.Notification.FirstOrDefault(x => x.ContractId == notificationEmail.ContractId);
if (notification == null)
{
_logger.LogInformation($"Creating new Notification for contract {notificationEmailType.ContractId}");
_context.Notification.Add(notificationEmail);
}
else
{
notification.IsInvitationActive = notificationEmail.IsInvitationActive;
notification.IsReminderActive = notificationEmail.IsReminderActive;
_logger.LogInformation($"Updating Notification for contract {notificationEmail.ContractId}");
}
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError("Error trying to create/update Notification", ex);
return false;
}
return true;