0

I have a model

public User
{
    public long Id {get;set;}
    public string UniqueUserId{get;set;}
    public string Company {get;set;}
    public string City {get;set;}
}

here Id is primary key with auto increment, Company and City which are the values entered by user. UniqueUserId is pattern value. its 16 digit value. It contains 1st 4 characters of Company, 4 characters from city and rest of digits are taken from the Id(suppose Id is 1 I will insert other digits as 0 using loop).

what I am actually doing now is that =>

  1. Read data from user
  2. Insert the data into context and then save changes
  3. Get the successfully inserted data from context
  4. Generate the UniqueUserId
  5. Update the entity and save the changes with context

I know there better methods to do this. But I don't get it. so any improved and better solution?

Ajit Hegde
  • 542
  • 1
  • 15
  • 33

2 Answers2

0

The main issue is trying to get the auto incremented Id before inserting. As per Can you get an auto incremented Id before saving? the suggested answer, is no / all "tricks" to circumvent that and determine the ID yourself are probably flawed.

There are other options including using a GUID instead for an id but that would depend on your requirements.

eVolve
  • 1,340
  • 1
  • 11
  • 30
-1

I declared UniqueUserId property like this:

    public  long Id { get; set; }
    public   string Company { get; set; }
    public   string City { get; set; }

    public string UniqueUserId
    {
        get
        {

            return  $"{Company[0]}{ Company[1]}{ Company[2]}{ Company[3]}{City[0]}{City[1]}{City[2]}{City[3]}{Id.ToString()[0]}{Id.ToString()[1]}{Id.ToString()[2]}{Id.ToString()[3]}{Id.ToString()[4]}{Id.ToString()[5]}{Id.ToString()[6]}{Id.ToString()[7]}";
        }
        set
        {

        }
    }

I hope it helps.