0

I want to join 2 tables using EF and check if there is any value

public bool IsSubscriptionExist(string domain)
{
    try
    {
        using (AccContext db = new AccContext ())
        {
            var count = (from s in db.Subscriptions
                         join a in db.Allias on s.Id equals a.Subscription_Id 
                         where (s.Domain == domain || a.Allias_Domain == domain)
                         select s).Count();

            return count > 0;
        }
    }
    catch (Exception ex)
    {
        customLogManager.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
        throw ex;
    }
}

The problem is that count returns 0 while subscription record is exist, I think because Allias is not exist. This is the same as join/left join I believe.

Is there any way to count even if Allias not exist ?

4
  • 2
    DefaultIfEmpty Commented Jan 7, 2018 at 23:32
  • 1
    You are doing an INNER JOIN, look up how to do a LEFT JOIN with entity framework Commented Jan 7, 2018 at 23:33
  • I did try to check ef left join but I didn't had any success with the code. I just cant figure what I'm doing wrong with if Commented Jan 7, 2018 at 23:37
  • Try these to find the issue: 1) remove the where clause and see if you get anything like that. If yes, that is the culprit. 2) See what query is generated and then execute the query directly against the db. Maybe that will point you in the right direction. Commented Jan 7, 2018 at 23:54

1 Answer 1

1

As stated on:

https://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9#leftouterjoin

public bool IsSubscriptionExist(string domain)
    {
        try
        {
            using (AccContext db = new AccContext ())
            {
                var count = (from s in db.Subscriptions
                             join a in db.Allias on s.Id equals 
                             a.Subscription_Id into ps
                             from a in ps.DefaultIfEmpty()
                             where (s.Domain == domain || a.Allias_Domain == domain)
                             select s).Count();

                return count > 0;
            }
        }
        catch (Exception ex)
        {
            customLogManager.Error(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
            throw ex;
        }
    }

Hope it will work for you

Sign up to request clarification or add additional context in comments.

1 Comment

Replace Count() with Any(). There is no need to get count and check it, using Any() is sufficient for this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.