Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi here is my code, doesn't seem to work. I am not sure what I'm missing I see the reference is generated but at the end its not inserted:

string jobRef = new Random().Next(1000, 9999).ToString();

                if (ModelState.IsValid)
                {
                    var model = new Job
                    {                  
                        Name = job.Name,
                        JobNo = job.JobNo,
                        Description = job.Description,
                        Location = job.Location,
                        CustomerId = job.CustomerId,
                        JobCategoryId = job.JobCategoryId,                                     
                        CreatedDate = DateTime.Now,
                        Reference = DateTime.Now.ToString("yyyyMM") + "-" + jobRef,
                    };
                    _context.Add(job);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Inprogress));
                }


Reference its a string on my model
public string Reference { get; set; }


Please kindly assist what am I doing wrong

What I have tried:

Please check above code, the reference is generated successfully but not inserted
Posted
Updated 8-Apr-21 19:21pm
Comments
The Other John Ingram 9-Apr-21 0:01am    
Change string jobRef = new Random().Next(1000, 9999).ToString();
to
Random r = new Random();
string jobRef = r.Next(1000,9999).ToString();

and see if this works
Nathi Mabinza 9-Apr-21 0:27am    
Just tried it now, when it hits _context.Add(job) the value of Reference its null
BillWoodruff 9-Apr-21 1:23am    
put a breakpoint before _context.Add(job);

inspect the value of Reference
Richard MacCutchan 9-Apr-21 5:18am    
Don't rely on random number generators as they can repeat the same values, so you could get two entries with the same number. Use an IDENTITY field in your database which is guaranteed unique.

1 solution

Missing
_context.Add(model)
. Its works.
 
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