Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用TPH找出实体框架中给定主键的类型_C#_Mysql_.net_Entity Framework_Tph - Fatal编程技术网

C# 使用TPH找出实体框架中给定主键的类型

C# 使用TPH找出实体框架中给定主键的类型,c#,mysql,.net,entity-framework,tph,C#,Mysql,.net,Entity Framework,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 : Accoun

我有以下情况:

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; }
}
我使用的是实体框架,因此数据库中只有一个表同时保存CheckingAccount记录和SavingAccount记录,该表将包含一个名为Discriminator的列,该列分别填充值“CheckingAccount”或“SavingAccount”

现在,我想将主键(Guid)作为输入,并找出该主键所属记录的类型

我有一个给定的Guid,想知道此Guid的记录是CheckingAccount记录还是SavingAccount记录

我试过这样的方法:

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:当记录是一个储蓄账户时,它会说

“请求CheckingAccount类型的实体时,找到的实体的类型为SavingAccount。”

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


我如何才能找出只给出主键的类型以及它可能属于的两种类型?

您是否尝试使用
var
object
作为
ca
sa
的类型

尝试一下:

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!");
    }
}

您可以通过基本实体
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!");
}
var account=ctx.Set().Find(pKey);
如果(帐户正在检查帐户)
{
控制台。WriteLine(“这是一个支票账户!”);
}
else if(账户为储蓄账户)
{
Console.WriteLine(“这是一个储蓄账户!”);
}

不幸的是,这也不起作用。甚至在将结果分配给变量之前,Find()方法本身也会引发异常。这些类型是否来自不同的sql表?否,所有记录都存储在一个名为“Account”的表中。该表包含一个名为“Discriminator”的列。在该列中,保存新记录时会自动存储类型的名称(“CheckingAccount”或“SavingAccount”)。是的,这很有效!非常感谢。不幸的是,我的支持率不高,因为我的声誉太低。