简体   繁体   中英

SQL to Entity Framework Using "In"

I've got an ASP.NET MVC application using EF in C#. I can write and run my query correctly in SQL Server. In EF, I'm not sure how to accomplish the same thing.

Tables A, B and C. C references B which References A.

The query looks like this:

Select * 
From C
Where C.bID in (Select B.bID 
                From B
                Where B.aID = '<unique Key In A>')

The sub-query returns multiple B keys. Which then pass it through and look up the ID's in C. In short I'm looking up all data in C related to a key in A.

I just don't know how to put that into EF language. Or if it's even possible. The IN operator is what's throwing me on the conversion.

Example:

  var exampleList = _context.C
                        .Where(l => l.bId in (_context.B
                        .Where(p => p.aId = keyInA)));

"in" doesn't work here. Obviously. After I wrote this post I made sure of it.

Note: A:B has a 1:Many relation. B:C has a 1 to many relation. All IDs and keys are GUIDs

Set up the navigation property between C & B, and between A & B. This is pretty much the whole point of using Entity Framework rather than just an alternative to ADO and SQL queries.

C contains a BId, so set up a B navigation property:

public class C
{
    public int CId { get; set; } 
    [ForeignKey("B")]
    public int BId { get; set; }
    public virtual B B { get; set; }
}

B contains an AId, so similar:

public class B
{ 
    public int BId { get; set; }
    [ForeignKey("A")]
    public int AId { get; set; }
    public virtual A A { get; set; }
}

Now, to write your query:

var cs = context.Cs.Where(x => x.B.AId == id);

or

var cs = context.Cs.Where(x => x.B.A.AId == id); // can filter on other "A" fields this way.

I mean, to avoid the use of navigation properties, you may as well just write Sprocs and use ADO. It is possible in cases where you have unrelated tables or absolutely need to avoid a navigation property. Use a Join between context.Cs and context.Bs:

var cs = context.Cs.Join(context.Bs, c => c.BId, b => b.BId, (c, b) => new { C = c, AId = b.AId })
                .Where(x => x.AId == aid)
                .Select(x => x.C);

IMO seriously ugly working with joins in EF, but sometimes necessary. If you can use a navigation property I'd highly recommend it over using something like that regularly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM