Cannot separate code when using DbContext

I always try to separate my code as much as possible. I’m fairly new to ASP.NET Core but the code principles and software design patterns are the same in all languages, however, when using entity-framework, there’s something that bothers me, or that I don’t know how to deal with.

In my application, I have users, which of course are created when registering. The users can add specific items to their inventory and request items to share from other users.

So I have a SharingRequests table, which has information such as UserBorrowerId, UserLenderId, InventoryItemId etc.

When I now want to create a sharing request and assign the user to it, I have to it all in the same context. For example, if I do this

MethodA: 
await using (var context = new DbContext())
{
    User user = context
        .Users
        .Where(u => u.Id == userId)
        .First();
}

methodB(user);
MethodB:
await using (var context = new DbContext())
{
    Item item = context
        .Items
        .Where(i => i.Id == itemId)
        .First();

    SharingRequest sharingRequest = new SharingRequest();
    sharingRequest.Item = item;
    sharingRequest.User = user;

    context.SharingRequests.AddAsync(sharingRequest);
    context.SaveChangesAsync();
}

I get the error that the user already exists in the database and it cannot create a new entry because of the duplicate key.

After googling this issue, I found that this is, because I have multiple database contexts, and the 2nd context doesn’t know about the first one.

However, this means, that EVERY entity that I need, which needs to be loaded etc. all needs to IN ONE await using (var context = new DbContext())

I fail to see how I can separate my code logically with this restriction. This forces me to have a method that does way too much things.

Why isn’t it possible to have a method to get the user, another one to build the sharing request (another one to do the validation) etc.?

Am I missing sth. completely here? I can’t imagine that this is the way applications have to be build because of the duplicate key problem.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes you are missing alot, firstly inject db context into the controller constructor and register in startup.cs, secondly have a method that gets the user and returns it. It has nothing to do with entity framework, just knowing how code works and post your actually method signatures.

How do you have multiple contexts? they both look exactly the same. Have you heard of unit of work pattern?

The error has nothing to do with db context, you are trying to create a user that already exists.

Do not use first always use firstordefault. You should check out codewithmosh he has a course on entity framework. Do not confuse clean code with functional code. You have to learn the basics of ef to apply clean code rules to it. Follow the path get it working, then clean it up.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x