繁体   English   中英

C#EntityFramework连接2个表并检查值是否存在

[英]c# entityframework join 2 tables and check if value exist

我想使用EF联接2个表并检查是否有任何值

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;
    }
}

问题是订阅记录存在时count返回0,我认为是因为Allias不存在。 这与我相信的连接/左连接相同。

即使Allias不存在,还有什么方法可以计数?

如上所述:

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;
        }
    }

希望它对你有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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