如果它们存在,我想从表a中选择值,但如果它们不存在则从b中选择值。在正常的查询中,我可以做leftjoin,但我不确定它是如何工作的
public static IEnumerable<dynamic> Foo(string somevalue, ref string errMessage)
{
try
{
var query= (from b in context.Tableb
join a in context.Tablea on b.value1 equals a.value1
where b.value1 == "somevalue"
select new Selectclass()
{
value1 = b.value1,
value2 = a.value2 ?? b.value2,
value3 = a.value3 ?? b.value3,
value4 = a.value4 ?? b.value4,
value5 = a.value5 ?? b.value5,
value6 = a.value6.ToString("dd-MM-yyyy"), //value7 is a DateTime in my Tables
value7 = a.value7
}).ToArray();
return query;
}
catch (Exception ex)
{
errMessage += (string.IsNullOrEmpty(errMessage) ? "" : Environment.NewLine) +
(string.IsNullOrEmpty(ex.Message) ? "" : ex.Message) +
(ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
MessageBox.Show(errMessage);
return null;
}
}
public class SelectClass
{
string value1 = String.Empty;
string value2 = String.Empty;
string value3 = String.Empty;
string value4 = String.Empty;
string value5 = String.Empty;
string value6 = String.Empty;
string value7 = String.Empty;
}
我的Tablea包含与Tableb相同的值,另外它包含Value6和Value7,我希望将其作为String.Empty返回,如果Tablea中不存在“somevalue”,则返回null
我回来的只是一个空的IEnum。有什么帮助吗?
答案 0 :(得分:0)
使用DefaultIfEmpty
模拟LINQ中的左连接:
var query= (from b in context.Tableb
where b.value1 == "somevalue"
join a in context.Tablea on b.value1 equals a.value1 into ja
from a in ja.DefaultIfEmpty()
select new Selectclass()
{
value1 = b.value1,
value2 = a?.value2 ?? b.value2,
value3 = a?.value3 ?? b.value3,
value4 = a?.value4 ?? b.value4,
value5 = a?.value5 ?? b.value5,
value6 = a?.value6.ToString("dd-MM-yyyy"), //value7 is a DateTime in my Tables
value7 = a?.value7
}).ToArray();