Home > database >  How to save an Id into a variable in EntityFrameworkCore and SQLite
How to save an Id into a variable in EntityFrameworkCore and SQLite

Time:06-15

I am very new to the Entity Framework Core and working with SQL

I have created a table called 'User' in a database and everytime I a new user is created, a new Id is also generated since it is a primary key. I want to be able save the users Id when they login, so that if they add a new workout to the workout table, then it will be saved with their Id.

I have tried:

                foreach (var field in data)
                {
                    if (context.User.Any(user => user.Name == UserName && user.Password == PassWord))
                    {
                        int UserID = context.User.Any(user => user.Id = UserID);
                    }

But I still don't exactly know how the queries work

Please help me.

CodePudding user response:

Any returns a boolean.

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-6.0

So the .Any in your first statement is "technically ok", but you end up doing 2 checks to find the object (your "User")....and your second Any doesn't seem correct.

See the below:

https://www.learnentityframeworkcore.com/dbset#retrieving-an-entity

So you might want to try FirstOrDefault

(the below is a modified version that comes from the "learning efcore" website above.

int primaryKey = 0;

using (SampleContext context = new SampleContext())
{
    Author foundAuthor = context.Authors.FirstOrDefault(a => a.LastName == "Shakespeare");
    if (null != foundAuthor) 
{
   primaryKey = foundAuthor.AuthorKey;
}
}

You can also try

SingleOrDefault

where the "Single" will throw an exception if more than 1 row is found. (Your code as-is has a pitfall of finding more than one match....maybe you have a unique-constraint on username...but it isn't shown here.

Sidenotes:

your "for" loop .. looks very dangerous. how many times are you checking for the matching userid?

keeping passwords as plain text in your database is a HORRIBLE/DANGEROUS/SECURITY-ISSUE.

CodePudding user response:

Don't use .Any, use .FirstOrDefault and check for null. If your user is not null, you may access the Id property

  • Related