c#entityframework连接2个表并检查值是否存在
我想使用EF连接两个表,并检查是否有任何值c#entityframework连接2个表并检查值是否存在,c#,entity-framework,linq,C#,Entity Framework,Linq,我想使用EF连接两个表,并检查是否有任何值 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
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不存在。我相信这和join/left join是一样的
即使Allias不存在,也有办法数数吗 如上所述:
希望它对你有用
DefaultIfEmpty
您正在执行内部联接
,请查看如何使用实体框架进行左联接
。我尝试检查ef LEFT JOIN,但代码没有成功。我就是想不出我做了什么错事,如果用这些来找出问题:1)删除where子句,看看你是否得到了类似的东西。如果是,那就是罪魁祸首。2) 查看生成了什么查询,然后直接对数据库执行查询。也许这将为您指明正确的方向。将Count()
替换为Any()
。无需获取计数并进行检查,使用Any()
即可解决此问题。
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;
}
}