使用Fluent API添加唯一标识符 [英] Adding unique identifier with Fluent API

查看:77
本文介绍了使用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.

推荐答案

幸运的是,EF Core允许您定义和使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆