Adding unique identifier with Fluent API

c# entity-framework-core fluent sql

Question

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.

1
1
4/13/2018 6:28:29 AM

Accepted Answer

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.

3
4/13/2018 6:28:07 AM


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