Search code examples
c#entity-frameworkcode-first

Create a complex Primary Key using Entity Framework code-first


I need to create a complex value via Entity Framework code-first, which includes three the following three values.

  • A is a constant part look like "s#34"
  • B is float and it's value come from a API webservice
  • C is natural number!

I want to C generate automatically . In one example we have these Ids :

+-----+------+--+
|A    |B     |C |
+-----+------+--+
|s#34 |67889 |1 |
|s#34 |68988 |2 |
|s#34 |87665 |3 |
|s#34 |35458 |4 |
|s#34 |..... |5 |
...

I'm looking for a code like this:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[ID = "string1" + "string2" + default.ToString()]
public int ID { get; set; }

my mean from "default" in code come back to the value that get from (DatabaseGeneratedOption.Identity).

Thank you for your help


Solution

  • Cramming all three pieces of information into one field would violate the single responsibility principle. You should probably create a composite key, and then combine in a computed column if you need to concatenate the three columns for display.