How to Auto Generate of Guid ID in .NET CORE 6?

Viewed 37

In my request data, if I have a duplication Guid ID, I want to generate a new Guid ID automatically. How to do it?

public class Roster { public Guid Id {get; set;} }

Here Guid Id is the primary key.

When I made an api post request, what would be the value I give for Guid Id?

1 Answers

If you use SQL and EntityFramework Core you could use this inside your model:

 [Key]
 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
 public Guid ActivityId { get; set; }

This will tell EF:

  • this property is the PRIMARY KEY of the table hence the [KEY]
  • this property should be automatically generated by the database

FYI you need to set a DEFAULT value for you SQL column like so: DEFAULT

  • (newsequentiaid()) tells SQL that he's in charge of creating a Globally Unique Id everytime you add a record to that table

Don't know if this is the answer you were looking for (nex time provide more info for us) anyway hope this helps you Cheers!

UPDATE

I do not know if my solution works with MySQL i use it for SQL. Searching a bit online i found no resources to newsequentialid in MySQL database (but i could be wrong, do your own research if you'd like).

Anyway i just don't set it for example:

 var activityDB = await context.Activity.FirstOrDefaultAsync(c => c.ActivityId == activity.ActivityId);
  if (activityDB == null)
  {
     activityDB = new Activity();
     context.Activity.Add(activityDB);
  }
     activityDB.Code = activity.Code;
     activityDB.Description = activity.Description;
     activityDB.Status = activity.Status;

Here's what the code does

  • check if my id exists if yes i have to edit if is null i don't
  • create new activity and edit
  • automatically EF nows what id to handle therefore no need to se it
  • If there is it means im editing for that id if not will create it automatically
Related