gpt4 book ai didi

c# - 使用 TPH 在 Entity Framework 中找出具有主键的类型

转载 作者:行者123 更新时间:2023-11-29 05:57:17 24 4
gpt4 key购买 nike

我有以下场景:

public abstract class Account
{
public Guid PKey { get; set; } = Guid.NewGuid();
public string Owner { get; set; }
}

public class CheckingAccount : Account
{
public int Fee { get; set; }
}

public class SavingAccount : Account
{
public double InterestRate { get; set; }
}

我正在使用 Entity Framework 和 Table per Hierarchy , 因此数据库中将有一个表同时包含 CheckingAccount-Records 和 SavingAccount-Records 并且该表将包含名为 Discriminator ,分别用值“CheckingAccount”或“SavingAccount”填充。

现在我想以一个主键(Guid)作为我的输入,找出这个主键所属的记录类型。

我有一个给定的 Guid,想知道这个 Guid 的记录是 CheckingAccount-Record 还是 SavingAccount-Record。

我试过这样的:

using(MyContext ctx = new Context())
{
CheckingAccount ca = ctx.CheckingAccount.Find(pKey);
SavingAccount sa = ctx.SavingAccount.Find(pKey);

if(ca != null)
{
Console.WriteLine("It's a CheckingAccount!");
}
else if(sa != null)
{
Console.WriteLine("It's a SavingAccount!");
}
}

但是,这会导致 InvalidOperationException:当记录是 SavingAccount 时,它会说

"The entity found was of type SavingAccount when an entity of type CheckingAccount was requested."

当我调用第一个 Find() 方法时。

如何仅给定主键和它可能属于的两种类型来找出类型?

最佳答案

您可以通过基本实体 DbSet 使用 EF 多态查询。像这样的东西应该可以完成这项工作:

var account = ctx.Set<Account>().Find(pKey);
if(account is CheckingAccount)
{
Console.WriteLine("It's a CheckingAccount!");
}
else if (account is SavingAccount)
{
Console.WriteLine("It's a SavingAccount!");
}

关于c# - 使用 TPH 在 Entity Framework 中找出具有主键的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48290005/

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