如果实体从基类继承,我该如何设置实体的ID?

发布于 2025-01-28 05:47:18 字数 814 浏览 3 评论 0 原文

我有以下结构:

public class EntityBase {
    public Guid? Id { get;set; }
    public Guid? TheRealId {get;set;}
}

public class SomeInheritEntity : EntityBase {
    string SomeOtherProp {get;set;}
}

EFCORE坚持认为, someneriteentity 中的真实ID是 ID 。由于我这是一个适配器,而且我无法可靠地依靠ID才能真正唯一,因此我添加了另一个我要确保是唯一的ID。

我如何让efcore使用 therealid 作为所有派生类型的ID entitybase

编辑: 我想避免分配所有 .haskey 之类的模式。也许有一个我可以使用的基础装饰器?

我尝试将 [键] 添加到基类 therealId ,但是EFCORE仍坚持使用 id> id 作为键,影响2行,旨在影响1种错误。

这起作用:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeInheritEntity>().HasKey("TheRealId");
}

但是我将为继承实体宣布这一点

I have the following structure:

public class EntityBase {
    public Guid? Id { get;set; }
    public Guid? TheRealId {get;set;}
}

public class SomeInheritEntity : EntityBase {
    string SomeOtherProp {get;set;}
}

EFCore insists that the real ID is Id in the SomeInheriteEntity. Since I this is an adapter, and I can't reliably count on Id to be truly unique, I've added another Id that I am going to ensure is unique.

How do I get EFcore to use TheRealId as the Id for all derived types of
EntityBase?

Edit:
I would like to avoid the pattern of assigning all of the .HasKey or the like in the Model Builder. Maybe there is a decorator for the base class I can use?

I attempted to add [Key] to the base class TheRealId, but efcore still insisted on using id as the key when doing updates and checking for affecting 2 rows, meant to affect 1 type of errors.

This works:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeInheritEntity>().HasKey("TheRealId");
}

But i would be declaring this for tons of inherit entities

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月野兔 2025-02-04 05:47:18

您可以配置 entityBase ,然后每个派生的类型配置为 entitybase 作为基本类型。

我建议将HASKEY MEDAGE超载与表达式使用,而不是字符串。这应该解决INT/GUID问题。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityBase>().HasKey(e => e.RealId);
    modelBuilder.Entity<SomeInheritEntity>().HasBaseType<EntityBase>();
    ...
}

You can configure EntityBase and then every derived type configure to set EntityBase as base type.

I would suggest using HasKey method overload with expression, instead of string. That should solve int/Guid issue.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityBase>().HasKey(e => e.RealId);
    modelBuilder.Entity<SomeInheritEntity>().HasBaseType<EntityBase>();
    ...
}

EntityTypeBuilder.HasBaseType Method

EntityTypeBuilder.HasKey Method

EF Core Inheritance

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文