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.
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.