使用Fluent API添加唯一标识符 [英] Adding unique identifier with Fluent API
问题描述
我使用的是我无法控制的模型,该模型将其实例保存在SQL数据库中.
I'm using a model which I have no control over, which I am saving instances of in a SQL database.
我正在使用Fluent API在此模型中向属性添加主键
I'm using Fluent API to add a primary key to an attribute in this model
modelBuilder.Entity<Message>().HasKey(d => d.DocumentId);
消息
看起来像这样:
[Required]
public Guid DocumentId { get; set; }
[Required]
public int Size { get; set; }
public string SenderId { get; set; }
但是,完全有可能接收到两个具有相同 DocumentId
的 Message
.通常,当使用 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
之类的东西进行保存时,我通常会要求SQL添加一个唯一标识符,但是由于我没有对 Message
的控制,我会处理吗?
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.
例如,以下流利的配置将创建名为"Id"的标识列并将其用作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
和 HasKey
是多余的,因为按惯例,名为"Id"的属性为PK,而按惯例, int
类型的PK为自动生成的,但是为了完整起见,我添加了它们.
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.
但是请注意,使用影子PK会更加困难.添加很容易,但是读取,更新和删除操作会出现问题.可以在LINQ查询中使用 EF.Property
方法来引用影子PK,但是通常,如果要更新或删除记录,则需要一些辅助条件.
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.
这篇关于使用Fluent API添加唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!