简体   繁体   中英

c# entityframework join 2 tables and check if value exist

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 ?

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

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