EF Core-条件关系-垂直表格拆分

时间:2019-04-18 18:09:55

标签: c# entity-framework entity-framework-core

由于现有的数据库架构,我必须处理特殊的关系。 数据库: -表格Cat(编号,名称) -表狗(id,姓名) -查看动物:

SELECT 'C' + CAST(Id AS VARCHAR) AS AnimalId, Id AS OriginalId, Name, 1 AS AnimalType 
FROM Cat
UNION
SELECT 'D' + CAST(Id AS VARCHAR) AS AnimalId, Id AS OriginalId, Name, 2 AS AnimalType 
FROM Dog
  • 表格咨询(动物编号,日期)

现在,我需要从我的咨询实体导航到Cat。 我定义了四个实体:

  1. 动物
  2. 咨询

Consult-Animal关系没问题。 但是当AnimalType = 2时,我需要得到猫。

我想做的是这样的:

modelBuilder.Entity<Cat>()
    .HasOne(a => a.Animal)
    .WithOne(a => a.Cat)
    .HasForeignKey<Cat>(k => k.Id)
    .HasPrincipalKey<Animal>(pk => pk.OriginalId && pk.AnimalType == 1);

SQL联接应该是这样的:

SELECT Animal.*, Cat.*
FROM Animal LEFT JOIN 
    Cat ON (Animal.OriginalId = Cat.Id AND Animal.AnimalType = 1)

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以像这样进行加入

from a in context.Animal
join c in context.Cat
on new {a.OriginalId, a.AnimalType} equals {c.Id, 1}
select new {a, c}