繁体   English   中英

使用TPH在Entity Framework中使用主键找出类型

[英]Find out type with primary key given in Entity Framework using TPH

我有以下情况:

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与每个层次结构的表一起使用,以便数据库中将有一个包含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时,它将说

“当请求类型为CheckingAccount的实体时,发现的实体为SavingAccount类型。”

当我调用第一个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!");
}

您是否尝试过使用varobject作为casa的类型?

试试看:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM