Skip to content

Instantly share code, notes, and snippets.

@mythz mythz/main.cs
Created Apr 8, 2019

Embed
What would you like to do?
SqlExpressionSelectFilter JoinAlias
using ServiceStack;
using ServiceStack.Text;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Sqlite;
using ServiceStack.DataAnnotations;
var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
var db = dbFactory.Open(); // Open ADO.NET DB Connection
OrmLiteUtils.PrintSql();
public interface IJoinFilter
{
int FirstTableId { get; set; }
}
public class FirstTable
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public bool Deleted { get; set; }
}
public class SecondTable : IJoinFilter
{
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
public int FirstTableId { get; set; }
public bool Deleted { get; set; }
}
db.DropAndCreateTable<FirstTable>();
db.DropAndCreateTable<SecondTable>();
var a = new FirstTable { Deleted = false };
db.Save(a);
db.Insert(new SecondTable { FirstTableId = a.Id, Deleted = false });
db.DropAndCreateTable<FirstTable>();
db.DropAndCreateTable<SecondTable>();
a = new FirstTable { Deleted = false };
db.Save(a);
db.Insert(new SecondTable { FirstTableId = a.Id, Deleted = false });
OrmLiteConfig.SqlExpressionSelectFilter = q =>
{
if (q.ModelDef.ModelType.HasInterface(typeof(IJoinFilter)))
{
q.LeftJoin<IJoinFilter, FirstTable>((f, j) => f.FirstTableId == j.Id)
.Where<FirstTable>(j => j.Deleted != true);
}
};
var q = db.From<SecondTable>(db.TableAlias(nameof(SecondTable)))
.Where<SecondTable>(x => x.Id == 1);
var result = db.Select(q);
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ServiceStack.Text" version="5.5.0" targetFramework="net45" />
<package id="ServiceStack.Interfaces" version="5.5.0" targetFramework="net45" />
<package id="ServiceStack.Common" version="5.5.0" targetFramework="net45" />
<package id="ServiceStack.OrmLite" version="5.5.0" targetFramework="net45" />
<package id="ServiceStack.OrmLite.Sqlite.Windows" version="5.5.0" targetFramework="net45" />
</packages>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.