LinqToSQL左外部联接

时间:2019-06-25 15:59:29

标签: c# linq-to-sql

我想复制此sql查询,但我很难找到解决方案;

SELECT C.Propref
FROM [dbo].[ClientProperties] C
LEFT OUTER JOIN  [dbo].[Properties] P ON C.[PROPREF] = P.[PROPREF] AND P.Contract = 'TXT'
WHERE P.[PROPREF] IS null

这是我要去的地方,但出现的错误是“在对象实例中未设置对象引用”。

var query = (from c in ClientProperties()
                    join p in db.Properties.Where(wc => wc.Contract == _contractId) on c.Place_reference equals p.Theirref into cp
                    from found in cp.DefaultIfEmpty()
                    select new
                    {
                        UPRN = c.Place_reference,
                    }).ToList();

对不起,我非常新手。 ClientProperties的定义是,它用于从csv文件的整理中整理数据。

    private IEnumerable<ClientProperty> ClientProperties()
    {
        CsvContext cc = new CsvContext();

        if (Directory.Exists(_interfaceInProperty))
        {
            IEnumerable<ClientProperty> properties = new List<ClientProperty>();
            var files = Directory.GetFiles(_interfaceInProperty, "Prop*.csv");

            foreach (var f in files)
            {
                properties = cc.Read<ClientProperty>(f, inputFileDescription);
            }
            return properties;
        }

        return null;

    }

2 个答案:

答案 0 :(得分:0)

是这样吗?:

var query = db.ClientProperties.GroupJoin(
    db.Properties,
    a => a.PROPREF,
    b => b.PROPREF,
    (a, b) => new { ClientProperties = a, Properties = b })
    .SelectMany(x => x.ClientProperties.Where(y => y.Contract == "TXT" && string.IsNullOrEmpty(y.PROPREF.ToString())),
    (a, b) => new { ClientProperties = a, Properties = b }).ToList();

我认为您的“ ClientProperties()”对象是上下文或类似内容。在这种情况下,您需要执行以下操作:

using (var db = new ClientProperties())
{

    var query = db.ClientProperties.GroupJoin(
        db.Properties,
        a => a.PROPREF,
        b => b.PROPREF,
        (a, b) => new { ClientProperties = a, Properties = b })
        .SelectMany(x => x.ClientProperties.Where(y => y.Contract == "TXT" && string.IsNullOrEmpty(y.PROPREF.ToString())),
        (a, b) => new { ClientProperties = a, Properties = b }).ToList();

}

然后您可以轻松访问该对象:

var response = query.FirstOrDefault().ClientProperties.Propref;

foreach (var item in query)
{
    var each_response = item.ClientProperties.Propref;
}

答案 1 :(得分:0)

您好,谢谢您的建议,因为它可以帮助我解决这是我的最终结果;

age