【问题标题】:Items list with discriminators带有鉴别器的项目列表
【发布时间】:2014-09-04 15:36:40
【问题描述】:

假设我有一个实体和一个名为Client 的数据库表。 Client 有一个外键 - CountryId 连接到 Countries 表。

ClientAClientBClientC 继承自 Client

我想列出我系统中的所有客户端(包括那些具有 null countryId 的客户端),以及它们的具体类型(鉴别器值)和国家/地区名称。

我的查询如下所示:

from client in DbContext.Set<Client>()
                    from country in DbContext.Set<Country>().Where(x => x.Id == client.CountryId).DefaultIfEmpty()
                    where !(client is Salon)                         
                    select new
                    {
                        Id = client.Id,
                        Name = client.ClientName,
                        ClientClass = "TODO",
                        CountryName = country.CountryName
                    };

我的问题:如何选择鉴别器值?请注意我目前卡住的代码中的“TODO”..

谢谢!

【问题讨论】:

  • 如果你只想要一个类型名称的字符串,client.GetType().ToString() 不会成功吗?
  • 我的错,错过了“具体类型”的要求...client.GetType() 在这种情况下?
  • 我已经尝试过了,但没有成功。我得到了:System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Type GetType()' method, and this method cannot be translated into a store expression
  • 哦,我不知道。去展示我对 LINQ to Entities 的了解;)

标签: c# entity-framework asp.net-mvc-4 n-tier-architecture


【解决方案1】:

鉴别器列由 Code First 内部使用,您不能从继承映射的角度读取/写入其值。

要获得鉴别器,您必须创建自定义 SQL 查询

context.Database.SqlQuery<T>("SELECT client.Id, client.ClientName, client.Discriminator, country.CountryName FROM Countries country LEFT JOIN Clients client ON country.Id = client.CountryId WHERE client.Discriminator <> 'salon'").ToList()

【讨论】:

  • 认真的吗?没有办法用 LINQ 获得这个值??问题中的查询已简化,所以我不会浪费您的时间。它实际上是一个相当大的 LINQ 查询,所以现在我需要将其切换为原生 SQL 查询吗?也许我最好再做一个查询来获得鉴别器,就是这样......
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 2022-01-16
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
相关资源
最近更新 更多