Skip to content

Instantly share code, notes, and snippets.

View afruzan's full-sized avatar
😎
I may be slow to respond.

afruzan afruzan

😎
I may be slow to respond.
View GitHub Profile
@afruzan
afruzan / RequestResponseLoggingMiddleware.cs
Created January 28, 2021 12:42
logging full request and responce (including body) in asp.net core (tested on 5 but should supports 3.1).
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace TVS.Web.DataReceiverService.Middlewares
private void sync<TEntity, TKey>(TEntity[] items, Func<TEntity, TKey> getId, TKey[] currentItemIds, out TKey[] keysToDelete, Action<TEntity> onAdd = null, Action<TEntity> onUpdate = null) where TEntity : class
{
foreach (var item in items)
{
if (currentItemIds.Contains(getId(item)))
{
_context.Entry(item).State = EntityState.Modified;
onUpdate?.Invoke(item);
}
else
// ef core 5
// after add/modify/delete some entities at a sync api, i recommend logging changes deeply.
// also it is best practice that returning the `changes` to client throw responce both in seccess and fail situation.
private object logContextChanges()
{
var changes = _context.ChangeTracker.Entries()
.Where(i => i.State != EntityState.Unchanged).Select(t => new
{
state = t.State.ToString(),
type = t.Entity.GetType().FullName,
@afruzan
afruzan / EFLinqExtensions.cs
Last active January 26, 2021 19:09
Useful EF6/EfCore LINQ Query Extensions
public static class EFLinqExtensions
{
public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IQueryable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<JoinTuple<TOuter, TInner>, TResult>> resultSelector)
{
return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, (b, @is) => new { b, @is }).SelectMany(i => i.@is.DefaultIfEmpty(), (b, i) => new JoinTuple<TOuter, TInner> { Outer = b.b, Inner = i }).Select(resultSelector);
}
public static IEnumerable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<JoinTuple<TOuter, TInner>, TResult> resultSelector)
{