Permalink
Browse files

Include aliases when selecting matching fields from different tables

  • Loading branch information...
mythz committed Nov 29, 2018
1 parent 44a52e1 commit d5b521407a08d47146a61b10263dac2bb9eb9e7e
@@ -1922,7 +1922,8 @@ private object SetAnonTypePropertyNamesForSelectExpression(object expr, Expressi
// When selecting a column use the anon type property name, rather than the table property name, as the returned column name
if (arg is MemberExpression propExpr && IsLambdaArg(propExpr.Expression))
{
if (propExpr.Member.Name != member.Name)
if (propExpr.Member.Name != member.Name || // Use anon property alias when names don't match
propExpr.Expression.Type != ModelDef.ModelType) // or when selecting a field from a different table
return new SelectItemExpression(DialectProvider, expr.ToString(), member.Name);
return expr;
@@ -2880,7 +2881,8 @@ public override string ToString()
{
var text = SelectExpression;
if (!string.IsNullOrEmpty(Alias)) // Note that even though Alias must be non-empty in the constructor it may be set to null/empty later
text += " AS " + DialectProvider.GetQuotedName(Alias);
return text + " AS " + DialectProvider.GetQuotedName(Alias);
return text;
}
}
@@ -832,6 +832,9 @@ public static string StripQuotes(this string quotedExpr)
return quotedExpr.Trim(QuotedChars);
}
public static void PrintSql() => OrmLiteConfig.BeforeExecFilter = cmd => Console.WriteLine(cmd.GetDebugString());
public static void UnPrintSql() => OrmLiteConfig.BeforeExecFilter = null;
public static ModelDefinition GetModelDefinition(Type modelType)
{
@@ -898,6 +898,34 @@ public void Can_populate_multiple_POCOs_using_SelectMulti3()
AssertMultiCustomerOrderResults(sb);
}
[Test]
public void Can_custom_select_from_multiple_joined_tables()
{
ResetTables();
AddCustomerWithOrders();
var q = db.From<Customer>()
.Join<Customer, CustomerAddress>()
.Join<Customer, Order>()
.Where(x => x.Id == 1)
.And<CustomerAddress>(x => x.Country == "Australia")
.OrderByDescending<Order>(x => x.Id)
.Take(1)
.Select<Customer,CustomerAddress,Order>((c,a,o) => new {
o.Id,
c.Name,
CustomerId = c.Id,
AddressId = a.Id,
});
var result = db.Select<(int id, string name, int customerId, int addressId)>(q)[0];
Assert.That(result.id, Is.EqualTo(2));
Assert.That(result.name, Is.EqualTo("Customer 1"));
Assert.That(result.customerId, Is.EqualTo(1));
Assert.That(result.addressId, Is.EqualTo(1));
}
private static void AssertMultiCustomerOrderResults(StringBuilder sb)
{
Assert.That(Regex.Replace(sb.ToString(), @"\.99[0]+",".99").NormalizeNewLines().Trim(), Is.EqualTo(

0 comments on commit d5b5214

Please sign in to comment.