gpt4 book ai didi

entity-framework-core - EF Core 处理备用主键

转载 作者:行者123 更新时间:2023-12-02 20:05:15 25 4
gpt4 key购买 nike

我有一些使用 dotnet ef dbContext scaffold 构建的 EF Core 模型使用数据库优先方法生成模型。我的问题是数据库使用整数主键,用于将表链接在一起,但有一个基于字符串的索引,该索引将用作搜索表的合理索引。

但是:当我尝试使用 FindAsync("abc000") 时我收到完全预期的错误 The key value at position 0 of the call to 'DbSet<Entity>.Find' was of type 'string', which does not match the property type of 'long'.

那么,有两个问题:

  1. EF 如何确定主键是什么?
  2. 有什么方法可以重新调整它,以便我可以使用“查找”按名称搜索实体,但保留自动增量主键?
  3. 我更喜欢自动增量整数键作为连接表的字段,这是否很愚蠢?

它们看起来像这样:

class Entity
{
long Id;
string Key;
};

在 OnModelCreating 中:

modelBuilder.Entity<Entity>(entity =>
{
entity.ToTable("tb_entity", "main");

entity.HasIndex(e => e.Key)
.HasName("uq_entity_key")
.IsUnique();

entity.Property(e => e.Id).HasColumnName("_id");

entity.Property(e => e.Key)
.HasColumnName("key")
.HasMaxLength(255);
}

创建表的 SQL 如下所示:

CREATE TABLE [tb_entity]
(
_id BIGINT PRIMARY KEY IDENTITY(1,1),
key NVARCHAR(255) CONSTRAINT uq_entity_key UNIQUE NOT NULL,
);

最佳答案

  1. How did EF Figure out what the primary key was?

如果没有通过 [Key] 明确指定属性或HasKey流畅的 API,作者为 convention :

By convention, a property named Id or <type name>Id will be configured as the key of an entity.

您可以通过检查来查看该信息

var pk = context.Model.FindEntityType(typeof(Entity)).FindPrimaryKey();
  1. Is there any way I can re-jig this so I can use "Find" to search for entities by name, but keep the autoincrement primary keys?

你可以利用数据注释/Fluent API 来骗 EF Core Entity 的 PK是 Name ,但我不建议这样做,因为这会导致对 FK 关系的错误假设,而且总的来说是不好的。

相反,不要使用 Find/FindAsync专门用于 PK 的方法。 First , FirstOrDefault , SingleSingleOrDefault (及其 Async 对应项)允许您按任何条件进行搜索,例如而不是FindAsync("abc000")你会使用FirstOrDefaultAsync(e => e.Name == "abc000") .

唯一的区别是Find方法首先在本地缓存中搜索,这在大多数使用场景中没有太大好处。从另一边看,Find方法不支持急切加载,而后者则支持。后者是针对数据库执行的,并且由于该列上有唯一索引,因此它们应该具有足够的性能。

  1. Am I being stupid for preferring auto increment integer keys as the fields to join tables on?

这是非常标准的数据库设计,通常比自然 PK 更可取,我认为这没有任何问题。

关于entity-framework-core - EF Core 处理备用主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com