如何在C#中以Expression<Func<T,bool>>实现两个DBSet的LINQ关联查询
Got it, let's break this down. Your FindByCondition method operates on a single DBSet<T>, so we can't directly pass a join expression into it. Instead, we need to rewrite that join logic as a predicate for your Device entity using a subquery with Any()—this translates cleanly to an Expression<Func<Device, bool>> that your method can handle perfectly.
Step 1: Assume Your Entity Classes (for context)
First, let's confirm the structure of your entities (adjust if yours differ):
public class Device { public string TerminalId { get; set; } // Add your other Device properties here } public class DeviceBranch { public string TerminalId { get; set; } public string BranchCode { get; set; } // Add your other DeviceBranch properties here }
Step 2: Build the Predicate Expression
Here's how to create the expression that replicates your original JOIN logic:
string targetBranchCode = "YOUR_BRANCH_CODE"; // Replace with your actual branch code // The predicate: "Find all Devices where there exists a DeviceBranch with matching TerminalId and the target BranchCode" Expression<Func<Device, bool>> branchFilter = d => RepositoryContext.Set<DeviceBranch>().Any(db => db.TerminalId == d.TerminalId && db.BranchCode == targetBranchCode); // Now pass this to your FindByCondition method var filteredDevices = yourRepository.FindByCondition(branchFilter);
Step 3: Optional: Use Navigation Properties (If Available)
If you've set up navigation properties between Device and DeviceBranch (which is recommended for EF Core), you can simplify this even more. For example, if Device has a collection of DeviceBranch entities:
public class Device { public string TerminalId { get; set; } public ICollection<DeviceBranch> DeviceBranches { get; set; } }
Then your predicate becomes:
Expression<Func<Device, bool>> branchFilter = d => d.DeviceBranches.Any(db => db.BranchCode == targetBranchCode);
Why This Works
Entity Framework Core translates the Any() subquery into an efficient EXISTS clause in SQL, which is functionally equivalent to your original JOIN query. This fits the signature of your FindByCondition method because it's a predicate that evaluates each Device entity against the associated DeviceBranch data.
Just ensure your RepositoryContext is accessible where you're building this expression (dependency injection works great for this in most apps).
内容的提问来源于stack exchange,提问作者SINETHEMBA PAULA

