0

I have this code :

               try
                {
                    newJob.Company = ((CustomPrincipal)HttpContext.Current.User).MyUser.WorkinCompany;

                    Random rnd = new Random();
                    newJob.JobId = rnd.Next(1000000, 10000000); 

                    realjob.RelatedJobs.Add(newJob);
                    _db.Entry(realjob).State = EntityState.Modified;
                }
                catch (Exception e)
                {

                }

And I get this exception :

Attaching an entity of type 'MySolution.Models.Register.MyUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

How can I get rid of this exception? Thanks.

jason
  • 6,962
  • 36
  • 117
  • 198

2 Answers2

0

First of all, your random function rnd.Next(100000,1000000) will eventualy return an int that already exist in your database (maybe not the first 3 times you use it, but after some time, it is sure).

So it's no wonder you always get a duplicate primary key exception.

And then, using random is NOT the right way to generate a primary key for your new entities, consider options like:

  1. Querying the table to find the max value of the primary key, and add +1 to it, if it dosen't exist, put 1.

  2. Using database integrated indentity column and just add the entity without primary key and the primary key will be automaticaly generated

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62
  • 1
    I think you missed a zero in the original post. The random number generator goes from 1000000 to 10000000 (one million to 10 million). Incidentally, using a guid as a primary key [is a bad idea](http://www.nullskull.com/a/1504/why-guids-are-not-a-good-idea-for-sql-server-primary-keys.aspx) – Chris Dunaway Jan 05 '17 at 19:03
0

Duplicate (?) of:

Other [MAJOR] issues with your code not directly related to the error you are receiving since the error clearly states the problem is with the class DegerlemeTakip.Models.Register.MyUser...

Assuming JobID is the Primary Key of the Job class, setting it to a random value is not a good idea. Mark the JobID property as Database generated to let the DB worry about setting the key and remove the line that sets the PK to a random value.

Assuming:

public class Job
{
    [Key]        
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int JobID { get; set;}
}

Change your code to this:

try
{
    newJob.Company = ((CustomPrincipal)HttpContext.Current.User).MyUser.WorkinCompany;

    realjob.RelatedJobs.Add(newJob);
    _db.Entry(realjob).State = EntityState.Modified;
}
catch (Exception e)
{
     //Please do something with the exception!
}

Also, setting the state of realJob to Modified should be unnecessary. Remove this line unless you have a specific reason for it:

_db.Entry(realjob).State = EntityState.Modified;

If you must set the JobID randomly, you will need to check to make sure the randomly assigned JobID is not already in use before attempting to attach it to the data context:

    try
{
    newJob.Company = ((CustomPrincipal)HttpContext.Current.User).MyUser.WorkinCompany;

    Random rnd = new Random();
    newJob.JobId = rnd.Next(1000000, 10000000); 

    // Keep Trying Random JobIDs until one doesn't already exist in the database
    while(_db.Jobs.Any(j => j.JobID == newJob.JobID))
        newJob.JobId = rnd.Next(1000000, 10000000); 

    realjob.RelatedJobs.Add(newJob);
    _db.Entry(realjob).State = EntityState.Modified;
}
catch (Exception e)
{
     //Please do something with the exception!
}

There's still major issues with the code above, such as once you have 9,000,000 jobs in the table there will be no more IDs left to assign and your code will loop forever, but you can figure that out if you absolutely must set the key randomly from code.

Community
  • 1
  • 1
chambo
  • 491
  • 3
  • 8