I'm using a model which I have no control over, which I am saving instances of in a SQL database.
I'm using Fluent API to add a primary key to an attribute in this model
modelBuilder.Entity<Message>().HasKey(d => d.DocumentId);
Message
looks like this:
[Required]
public Guid DocumentId { get; set; }
[Required]
public int Size { get; set; }
public string SenderId { get; set; }
However it's entirely possible to receive two Message
's with the same DocumentId
. Normally I'd have SQL add a unique identifier when saving using something like [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
, but since I don't have control of Message
, how would I handle this?
Any hints greatly appreciated.
Luckily EF Core allows you to define and use Shadow property as PK.
For instance, the following fluent configuration will create identity column named "Id" and use it as PK:
modelBuilder.Entity<Message>()
.Property<int>("Id")
.ValueGeneratedOnAdd();
modelBuilder.Entity<Message>()
.HasKey("Id");
ValueGeneratedOnAdd
and HasKey
in this case are redundant, because property named "Id" by convention is PK and int
type PKs by convention are auto generated, but I've added them for completeness.
But please note that working with the shadow PK will be harder though. Adding is easy, but read, update and delete operations will be problematic. EF.Property
method can be used inside the LINQ queries to refer to the shadow PK, but in general you'd need some secondary criteria in case you want to update or delete a record.