Files
telegram-bot/Core/Extensions/DbContextExtension.cs
T

55 lines
1.8 KiB
C#
Raw Normal View History

2022-01-22 17:13:38 +03:00
using System;
using Microsoft.EntityFrameworkCore;
namespace Kruzya.TelegramBot.Core.Extensions;
public static class DbContextExtension
{
/// <summary>
/// Marks the entity as created.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as created.</param>
[Obsolete("DbContextExtension.MarkAsCreated is obsolete, use DbContext.Add instead")]
2022-01-22 17:13:38 +03:00
public static void MarkAsCreated(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Added;
/// <summary>
/// Marks the entity as deleted.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as deleted.</param>
[Obsolete("DbContextExtension.MarkAsDeleted is obsolete, use DbContext.Remove instead")]
2022-01-22 17:13:38 +03:00
public static void MarkAsDeleted(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Deleted;
/// <summary>
/// Marks the entity as modified.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as modified.</param>
[Obsolete("DbContextExtension.MarkAsModified is obsolete, use DbContext.Update instead")]
public static void MarkAsModified(this DbContext dbContext, object entity)
{
var entry = dbContext.Entry(entity);
if (entry.State == EntityState.Added)
return;
entry.State = EntityState.Modified;
}
2022-01-25 23:34:37 +03:00
public static void AddOrUpdate(this DbContext dbContext, object entity)
{
try
{
dbContext.Update(entity);
dbContext.SaveChanges();
}
catch (DbUpdateConcurrencyException e)
{
dbContext.Add(entity);
dbContext.SaveChanges();
}
}
2022-01-22 17:13:38 +03:00
}