Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi im new to C#
im trying to create a new costumer in my SQL database, when generating user ID to the SQL table, i have to check if ID is used, and if its used make error and set next number in the database as default for the new user, and show it to user before adding.

What I have tried:

// GET: Kundes/CreateOffentlig()
public ActionResult CreateOffentlig()
{
  ViewBag.KundeID = new SelectList(db.KundeOffentlig, "KundeID", "InstitutionsNavn");
  ViewBag.KundeID = new SelectList(db.KundePrivat, "KundeID", "PrivatMail");
  ViewBag.KundeID = new SelectList(db.KundeStorKunde, "KundeID", "FirmaNavn");
  Kunde kunde = new Kunde();
  kunde.KundeGr = 2;
  kunde.KundeID = db.Kunde.Max(p => p.KundeID) + 1;

  return View(kunde);
}

// POST: Kundes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOffentlig([Bind(Include = "KundeID,KundeGr,ForNavn,EfterNavn,Adresse1,Adresse2,PostNr,Mobil,InstitutionsNavn,CVRNummer,InstitutionsLeder,Mail")] Kunde kunde, KundeOffentlig kundeOffentlig)
{
  if (ModelState.IsValid) //Fejlhåndtering i forbindelse med id er brugt
  {
    try
    {
      kunde.KundeID = db.Kunde.Max(p => p.KundeID) + 1;
      kundeOffentlig.KundeID = kunde.KundeID;
      db.Kunde.Add(kunde);
      db.KundeOffentlig.Add(kundeOffentlig);
      db.SaveChanges();

      return RedirectToAction("Index");
    }
    catch (Exception)
    {
      ModelState.AddModelError("", "KundeID Already used ");

      return View(kunde);
    }
  }
}
Posted
Updated 25-Feb-19 21:32pm
v2
Comments
F-ES Sitecore 25-Feb-19 9:21am    
It's better to get the database to generate the new ID for you by using an identity column for the ID.
Kornfeld Eliyahu Peter 25-Feb-19 9:25am    
https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017

When creating a table make sure to have a primary key.
See explanation here SQL PRIMARY KEY Constraint[^]
If you do not want to recreate your table please follow the section
SQL PRIMARY KEY on ALTER TABLE

On table creation you should use Identity
e.g.
create table Example
(
   ID int IDENTITY(1,1) PRIMARY KEY,
   ...
)

as described in SQL AUTO INCREMENT a Field[^]
 
Share this answer
 
v3
Whereas Solution 1 will work to prevent duplicates, see the comment from S-ES Sitecore. Do not generate IDs by using "the next number" - what if two users try to update the table at the same time - you will get duplicate IDs.

You could use Identity - see Kornfeld Eliyahu Peter's comment IDENTITY (Property) (Transact-SQL) - SQL Server | Microsoft Docs[^]

Or you could use a sequence - The SEQUENCE, an updatable alternative for an IDENTITY column | Hans Michiels – Blog and more[^]
 
Share this answer
 
Comments
TheRealSteveJudge 25-Feb-19 10:08am    
You're right. Identity should be used. 5*
This worked for me :-)



if (ModelState.IsValid) //Fejlhåndtering i forbindelse med id er brugt
            {
                try
                {
                    
                    kundePrivat.KundeID = kunde.KundeID;
                    db.Kunde.Add(kunde);
                    db.KundePrivat.Add(kundePrivat);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception)
                {
                    int kundeID = db.Kunde.Max(p => p.KundeID) + 1;
                    ModelState.AddModelError("", "KundeID er allerede brugt. Nyt ID foreslået ;-)");
                    ModelState.SetModelValue("KundeID",
                        new ValueProviderResult(
                            kundeID,
                            kundeID.ToString(),
                            System.Globalization.CultureInfo.InvariantCulture
                        )
                    );
                    return View(kunde);

                }
 
Share this answer
 
Comments
CHill60 26-Feb-19 3:45am    
Don't blame us when you get duplicate IDs in a multi-user environment! You're a student who has had 4 experienced programmers - "experts" - tell you to not increment the "last number" on the database. This is the wrong way to go about this.
Dave Kreskowiak 26-Feb-19 8:16am    
It worked for you in as a SINGLE CONCURRENT USER of your code. The second you have more than 1 person hitting this code at the same time, it'll fall on its face and you end up with duplicate ID's in the table and other problems in the database related to those ID's. The problems will compound when you have related records, dependent on foreign keys, using those ID's and data will be lost. You will not be able to straighten that out because you won't be able to figure out which records in other tables belong to which records that have the duplicate ID's.

Again, DO NOT GENERATE YOUR OWN ID VALUES, EVER.

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