将复杂的LEFT OUTER SQL查询转换为LINQ

时间:2019-10-02 11:53:55

标签: entity-framework linq

我有一个(丑陋的)MS SQL public class map extends AppCompatActivity { ImageView ivMap_ActivityMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); ivMap_ActivityMap = (ImageView)findViewById(R.id.ivMap_ActivityMap); ivMap_ActivityMap.setImageResource(R.drawable.usa); ivMap_ActivityMap.setOnTouchListener(handleTouch); } private final View.OnTouchListener handleTouch = new View.OnTouchListener() { @SuppressLint("ResourceAsColor") @Override public boolean onTouch(View v, MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); Toast.makeText(map.this, "x = " + x + ", y = " + y, Toast.LENGTH_LONG).show(); Paint paint = new Paint(); int radius; radius = 100; paint.setStyle(Paint.Style.FILL); paint.setColor(R.color.colorPrimaryDark); Canvas canvas = new Canvas(); canvas.drawCircle(x, y, radius, paint); return true; } }; } 查询,我想用LINQ编写它。

LEFT JOIN

我知道我可以在连接中使用复合键,直到现在我才想到:

select a.VersionId 
FROM (SELECT root.VersionId, root.[Xml], versions.VersionId as replacedBy
  FROM [Entities] as root
    LEFT OUTER JOIN [Entities] as versions
    on root.EntityId = versions.EntityId AND root.VersionId = versions.ReplacedVersionID
      where root.EntityId = @EntityId) as a
where a.replacedBy IS NULL AND a.Xml IS NOT NULL

但是这就是我遇到的问题。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果分段翻译,这并不太复杂。

首先,将子查询转换为变量:

var asq = from root in entities
          where root.EntityId == EntityId
          join versions in entities on new { root.EntityId, root.VersionId } equals new { versions.EntityId, VersionId = versions.ReplacedVersionID } into versionsj
          from versions in versionsj.DefaultIfEmpty()
          select new {
              root.VersionId,
              root.Xml,
              replacedBy = versions.VersionId
          };

然后,翻译主要查询:

var ans = from a in asq
          where a.replacedBy == null && a.Xml != null
          select a.VersionId;