Entity Framework is it possible to generate string pattern value on adding entity to database?

asp.net-core c# database entity-framework entity-framework-core

Question

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?

1
0
1/3/2019 5:31:18 PM

Accepted Answer

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.

0
1/3/2019 6:54:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow