c# linq 在 tph 中获取数据库中项目的类型

c# linq get type of item in database in tph

我有一个 wpf 应用程序,其中的数据库首先使用 Entity Framework 代码创建。

我有一个 class Shoes.cs 和两个 class 继承自鞋子:Canvas.csBoots.cs

对于映射,我使用了 tph 方法,所以我有一个 table 鞋子,它有一个鉴别器,用于识别是 canvas 还是靴子

我必须在数据网格中显示我所有的鞋子及其类型。我知道我不能直接查询鉴别器列,所以我试图做这样的事情

 var allShoes = (from shoes in db.Shoes
                 select shoes).ToList();

        List<string> typeOfShoes = new List<string>();

        foreach (Shoes pairShoes in allShoes)
        {
            if (pairShoes.GetType() == typeof(Canvas))
            {
                typeOfShoes .Add("Canvas");
            }
            else if (pairShoes.GetType() == typeof(Boots))
            {
                typeOfShoes .Add("Boots");
            }
            else
            {
                typeOfShoes .Add("Wrong");
            }
        }

我可以获取数据网格中的所有内容,但在列类型中仅显示 "Wrong"。

如何获得鞋子的类型?

您目前正在询问 class Shoes 的类型,您应该询问实例的类型。此外你还应该使用is。此运算符检查对象是否与给定类型兼容,而不是依赖于确切的类型。

if (pairShoes is Canvas)
        {    
         ....