【问题标题】:How to get the 'type name' of an derived entity within LINQ statement : "does not recognize the method 'System.Type GetType()"如何在 LINQ 语句中获取派生实体的“类型名称”:“无法识别方法 'System.Type GetType()”
【发布时间】:2015-04-23 22:14:17
【问题描述】:

我想知道是否有可能获得从同一基本实体继承的实体类型。当我使用以下内容时

   var db.BaseClass.Select(a => new { Type = a.GetType().Name });

我收到"LINQ to Entities does not recognize the method 'System.Type GetType()' method" 错误。我需要知道从基类继承的实体的类名。我知道我可以用这个:

  var derivedClass1Items = db.BaseClass.OfType<DerivedClass1>().Select(a => new { Type = "DerivedClass1" });
   var derivedClass2Items = db.BaseClass.OfType<DerivedClass2>().Select(a => new { Type = "DerivedClass2" });

但是,这看起来很麻烦。有没有办法通过第一种方法来做到这一点,将BaseClass 与单个 LINQ 语句一起使用?

更新

这是我真正的课程:

Like : LikeId, LikeDate, WhoLiked, WhoseLiked *基类

PostLike: PostId *继承的类

CommentLike: CommentId *继承的类

ReplyLike:ReplyId *继承类

【问题讨论】:

  • 为什么要首先选择类型列表?这样做似乎没有实际的理由?您最终将得到的只是一个类型列表,没有有意义的数据将其与实体联系起来,这似乎是一个 XY 问题。
  • @AllMadHare 当然我还有一些其他属性,但这里没有包括它们,因为它们与实际问题无关。
  • 最终,LINQ 查询必须转换为 SQL 查询。 LINQ to entity 不知道如何将GetType() 转换为 SQL 函数(没有等效的 SQL 函数)。您必须先执行查询并使用内存中的结果对象进行投影:db.BaseClass.AsEnumerable().Select(x =&gt; new { Type = x.GetType().Name })。不过,我很想知道BaseClass 是如何定义的。您是否先使用 EF 代码创建它?
  • @JasonBoyd 是的,这是 EF 代码,我首先添加了我的课程。
  • 好的,我仍在努力思考它在实践中的工作原理。在我看来,db.BaseClass 总是会返回基类对象。我认为它永远不会返回更派生的类型。

标签: c# linq entity-framework inheritance


【解决方案1】:

我认为这是你最好的解决方案

var db.Likes.Select(a => new 
    {
        Type = a.PostLike != null 
                ? "PostLike" 
                : a.CommentLike !=null 
                    ? "CommentLike" 
                    : a.ReplyLike != null 
                        ? "ReplyLike"
                        : null
    });

但是这样你需要离开继承来使用 0:1 导航属性来代替

【讨论】:

    猜你喜欢
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2022-01-21
    • 2013-08-30
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    相关资源
    最近更新 更多