Click here to Skip to main content
15,886,773 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have register 5 users in my app. I need assigning ramdom number for all of them but I cant

What I have tried:

public ActionResult Test(User user )
        {
            
            Random rand = new Random();
            int numero = rand.Next(1, 10000);
            var model = new User();

            model.UserId = user.UserId;
            model.Nombre = user.Nombre;                     
            model.Codigo = numero;

            
            db.Users.Add(model);
            db.SaveChanges();
            return View(model);
            
        }
Posted
Updated 18-Oct-17 4:52am
v4
Comments
Dave Kreskowiak 17-Oct-17 21:57pm    
I don't know what "assing" means but it sounds not like it's not kid-sister-safe.

If you're talking about "assigning" numbers to users, the question becomes why?
NerakSeven 17-Oct-17 22:01pm    
yes "assigning" sorry fr my english. I need it because it's like a password
Patrice T 17-Oct-17 22:08pm    
Use Improve question to update your question.
Dave Kreskowiak 17-Oct-17 23:04pm    
OK, so PIN numbers are usually a certain length. Your "random" number is anywhere between 1 and 4 digits long.

Did you want to tell everyone what the problem is?
NerakSeven 17-Oct-17 23:20pm    
the problem is that the method creates a new record, not insert the PIN to existing users

1 solution

OK, if you're trying to update an existing record, what do you think db.Users.Add does? Your code is specifically creating a new user and saving it to the table!

You have to retrieve the existing user object(s) from the database, assign the random numbers to them, then save the changes back to the database.

C#
Random rand = new Random();
var users = db.Users;

foreach (var user in users)
{
    // Assign a 4 digit PIN
    user.Codigo = rand.Next(1000, 10000);
}

db.SaveChanges();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900