c# - 原始痴迷 - 具有自动增量的强类型 int ID

标签 c# sql-server .net-core entity-framework-core domain-driven-design

如何获取强类型的 Id...

public sealed class FileUploadId
{
    public int Value { get; }

    public FileUploadId(int value)
    {
        Value = value;
    }
}

...在我的 FileUpload 类中使用...

public class FileUpload : EntityBase, IAggregateRoot
{
    private FileUpload() { /* Required by EF */ }

    public FileUpload(string name, string relativePath, FileUploadType type, string contentType, long? size = null)
    {
        /* Guard clauses... */

        Id = new FileUploadId(0);

        /* Other properties... */
    }

    public FileUploadId Id { get; }

    /* Other properties... */
}

...使用标识(int 自动递增)?

我在我的 TypeConfiguration 中尝试了 ValueGeneratedOnAdd(),但没有成功...

public class FileUploadTypeConfig : IEntityTypeConfiguration<FileUpload>
{
    public void Configure(EntityTypeBuilder<FileUpload> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).HasConversion(x => x.Value, x => new FileUploadId(x)).ValueGeneratedOnAdd();

        /* Other configurations... */
    }
}

我知道HiLo 算法 还有另一种选择。但我想让它使用默认的 int id 增量。这有可能吗?

最佳答案

我通过以下方式使用 .net6 和 EFCore6 获得了具有自动递增整数的强类型 ID:

  • 配置.HasConversion()
  • 添加 .ValueGeneratedOnAdd()
  • 添加 .Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore)
  • 确保强类型 ID 永远不会为 null

编辑: 这种方法有一个缺陷。

它与更改跟踪有关。由于 ef core 3.0 和 this GitHub issue ,当您对键使用自动递增并且键值不是默认值时,实体将添加到“已修改”状态而不是“已添加”状态。这是当前解决方案的一个问题,因为我们从未为强类型 ID 设置 null。我们将不得不手动开始跟踪处于“已添加”状态的实体(使用 DbContext Add 方法),其他类型的自动跟踪将不起作用(例如,将实体添加到导航属性集合中以实现一对多关系).对此的官方支持正在跟踪 this GitHub issue .

关于c# - 原始痴迷 - 具有自动增量的强类型 int ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58629377/

相关文章:

c# - 使用 IConfigurationRoot 将环境变量绑定(bind)到类

c# - Content-Disposition 中的 HttpClient 编码错误

c# - 在构建服务器上注册 COM 引用的 DLL

sql-server - SQL Server 中的只读锁

sql - 表变量与临时表

sql - 如何在没有子查询的情况下找到最大值

c# - EF Core EnsureDeleted 抛出 "failed to login with user ' sa'"

c# - 当 Enumerable 在 Linq 中有超过 X 个元素时提前返回

c# - 在本地主机上模拟慢速互联网连接

c# - 微软图形 API : Getting error "Authorization_IdentityNotFound"