Skip to content

SaveChangesAsync is not working for different contexts #78

@fabercs

Description

@fabercs

https://github.com/Arch/UnitOfWork/blob/594a381dce2f6c55904967a6ea10b5a92ed0aeb7/src/Microsoft.EntityFrameworkCore.UnitOfWork/UnitOfWork.cs#L155

This SavecCangesAsync method is not convenient for multiple different contexts beacuse of casting issue.

Startup
services.AddUnitOfWork<BlogContext, BlogLogContext>();

Service

public class UserService : IUserService
{
    private readonly IUnitOfWork<BlogContext> _blogUnitOfWork;
    private readonly IUnitOfWork<BlogLogContext> _blogLogUnitOfWork;

    public UserService(IUnitOfWork<BlogContext> blogUnitOfWork, IUnitOfWork<BlogLogContext> blogLogUnitOfWork) {
        _blogUnitOfWork = blogUnitOfWork;
        _blogLogUnitOfWork = blogLogUnitOfWork;
    }

    public async Task<bool> DeleteAuthorWithEntireStuff(int id)
    {
        try
        {
            var userRepo = _blogUnitOfWork.GetRepository<User>();
            var postRepo = _blogUnitOfWork.GetRepository<Post>();
            var commentRepo = _blogUnitOfWork.GetRepository<Comment>();

            var logRepo = _blogLogUnitOfWork.GetRepository<Log>();

            var postList = postRepo.GetAll().Where(p => p.AuthorId == id).ToList();
            var commentList = commentRepo.GetAll().Where(c => c.UserId == id).ToList();

            userRepo.Delete(id);
            commentRepo.Delete(commentList);
            postRepo.Delete(postList);

            logRepo.Create(new Log
            {
                Message = $"All stuff of userId:{ id } has been deleted",
                Level = "Information",
                MessageTemplate = "Information",
                TimeStamp = DateTime.UtcNow.ToString(),
                Exception = null,
                LogEvent = null,
                Properties = null
            });

            // or await vice versa
            return await _blogUnitOfWork.SaveChangesAsync(_blogLogUnitOfWork)!=0;

        }
        catch (Exception)
        {
            throw;
        }
    }
}

UnitOfWork

foreach (var item in unitOfWorks)
                    {
                        var uow = item as UnitOfWork<DbContext>;
                        uow.Context.Database.UseTransaction(tran.GetDbTransaction());
                        count += await uow.SaveChangesAsync();
                    }

Here when I call SaveChangesAsync in UnitOfWork<BlogContext>, as TContext is BlogContext casting from BlogContext to BlogLogContext is not available, also from DbContext to BlogLogContext is not available as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions