Custom Mapping where source property does not exist - automapper

Is it possible to map from a source object to a destination object where the source object is different?
The config table has a related objects to the lookup tables via the Code property (kind of a loose coupling scenario)
ServiceLookup & ClassificationLookup cannot exist in the source object for legacy reasons.
These are the tables.
CREATE TABLE Config ( Id INT IDENTITY (1, 1) NOT NULL
, Code NVARCHAR (50) NOT NULL
, ServiceLookupCode NVARCHAR (50) NOT NULL
, ClassificationLookupCode NVARCHAR (50) NOT NULL
, SomeConfigValue NVARCHAR (50) NOT NULL
, CONSTRAINT PK_Table1 PRIMARY KEY CLUSTERED (Id ASC)
, CONSTRAINT UQ_Table1_Code UNIQUE NONCLUSTERED (Code ASC) );
CREATE TABLE ServiceLookup ( Id int IDENTITY(1,1) NOT NULL
, Code nvarchar(50) NOT NULL
, Name nvarchar(255) NOT NULL
, CONSTRAINT PK_ServiceLookup PRIMARY KEY CLUSTERED (Id ASC)
, CONSTRAINT UQ_ServiceLookup_Code UNIQUE NONCLUSTERED (Code ASC) );
CREATE TABLE ClassificationLookup ( Id int IDENTITY(1,1) NOT NULL
, Code nvarchar(50) NOT NULL
, Name nvarchar(255) NOT NULL
, CONSTRAINT PK_ClassificationLookup PRIMARY KEY CLUSTERED (Id ASC)
, CONSTRAINT UQ_ClassificationLookup_Code UNIQUE NONCLUSTERED (Code ASC) );
SQL Example to return the data
SELECT c.Id, c.Code, c.SomeConfigValue
, sl.Name AS ServiceName
, cl.Name AS ClassificationName
FROM Config c
INNER JOIN ServiceLookup sl ON c.ServiceLookupCode = sl.Code
INNER JOIN ClassificationLookup cl ON c.ClassificationLookupCode = cl.Code
Entities
The ServiceLookup and ClassificationLookup tables cannot be defined in the Config table (legacy reasons)
public class Config
{
public int Id { get; set; }
public string Code { get; set; }
public string ServiceLookupCode { get; set; }
public string ClassificationLookupCode { get; set; }
public string SomeConfigValue { get; set; }
//public ServiceLookup ServiceLookup { get; set; } <-- This is not allowed due to loose coupling design (legacy reasons)
//public ClassificationLookup ServiceLookup { get; set; } <-- This is not allowed due to loose coupling design (legacy reasons)
}
public class ServiceLookup
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class ClassificationLookup
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
DTO
public class ConfigDto
{
public int Id { get; set; }
public string Code { get; set; }
public string ServiceLookupCode { get; set; }
public string ClassificationLookupCode { get; set; }
public string SomeConfigValue { get; set; }
public LookupModel ServiceLookup { get; set; }
public LookupModel ClassificationLookup { get; set; }
public class LookupModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}
Linq code
var result = await (from c in Db.Config
join sl in Db.ServiceLookup on c.ServiceLookupCode equals dl.Code
join cl in Db.ClassificationLookup on c.ClassificationLookupCode equals cl.Code
select new ConfigDto
{
Id = c.Id,
Code = c.Code,
SomeConfigValue = c.SomeConfigValue,
ServiceLookupCode = c.ServiceLookupCode,
ClassificationLookupCode = c.ClassificationLookupCode,
ServiceLookup = new ConfigDto.LookupModel
{
Id = sl.Id,
CodePath = sl.Code,
Name = sl.Name
},
ClassificationLookup = new ConfigDto.LookupModel
{
Id = cl.Id,
Code = cl.Code,
Name = cl.Name
}
}
)

Related

Selecting OrmLite new object from joined table for insertion

I have 3 entities:
[CompositeIndex(nameof(Url), nameof(TargetDomainRecordId), nameof(UserAuthCustomId), Unique = true)]
public class WatchedUrlRecord
{
[AutoIncrement]
public long Id { get; set; }
public string Url { get; set; }
public string Provider { get; set; }
public string DomainKey { get; set; }
public WatchedUrlScanStatus WatchedUrlScanStatus { get; set; }
public bool NoFollow { get; set; }
public HttpStatusCode HttpStatusCode { get; set; }
public DateTime? LastScanTime { get; set; }
public WatchedUrlScanResult LastScanData { get; set; }
public string Anchors { get; set; }
public int? OutboundLinks { get; set; }
[ForeignKey(typeof(TargetDomainRecord), OnDelete = "CASCADE")]
public long TargetDomainRecordId { get; set; }
[ForeignKey(typeof(UserAuthCustom), OnDelete = "CASCADE")]
public long UserAuthCustomId { get; set; }
}
[CompositeIndex(nameof(Url), nameof(TargetDomainRecordId), nameof(UserAuthCustomId), Unique = true)]
public class WatchedUrlQueue
{
[PrimaryKey]
public long WatchedUrlRecordId { get; set; }
[Index]
public string Url { get; set; }
[Index]
public string DomainKey { get; set; }
[Index]
public long TargetDomainRecordId { get; set; }
public string TargetDomainKey { get; set; }
[Index]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
public int Tries { get; set; }
[Index]
public DateTime? DeferUntil { get; set; }
[Index]
public long UserAuthCustomId { get; set; }
[Index]
public bool FirstScan { get; set; }
}
[CompositeIndex(nameof(Url), nameof(UserAuthCustomId), Unique = true)]
public class TargetDomainRecord
{
[AutoIncrement]
public long Id { get; set; }
public string Url { get; set; }
public string DomainKey { get; set; }
public DateTime CreateDate { get; set; } = DateTime.Now;
public DateTime? DeleteDate { get; set; }
public bool IsDeleted { get; set; }
public bool Active { get; set; } = true;
public DomainType DomainType { get; set; }
[ForeignKey(typeof(UserAuthCustom), OnDelete = "CASCADE")]
public long UserAuthCustomId { get; set; }
}
I am trying to insert queue objects based on IDs of WatchedUrlRecords so I came up with this query:
var q = db.From<WatchedUrlRecord>()
.Where(x => Sql.In(x.Id, ids))
.Join<TargetDomainRecord>((w, t) => w.TargetDomainRecordId == t.Id)
.Select<WatchedUrlRecord, TargetDomainRecord>((w, t) => new WatchedUrlQueue()
{
UserAuthCustomId = w.UserAuthCustomId,
DomainKey = w.DomainKey,
CreateDate = DateTime.UtcNow,
DeferUntil = null,
FirstScan = firstScan,
TargetDomainKey = t.DomainKey,
Tries = 0,
TargetDomainRecordId = w.TargetDomainRecordId,
Url = w.Url,
WatchedUrlRecordId = w.Id
});
var inserted = db.InsertIntoSelect<WatchedUrlQueue>(q, dbCmd => dbCmd.OnConflictIgnore());
This doesn't work and gives error:
variable 'w' of type 'Project.ServiceModel.WatchedUrl.Entities.WatchedUrlRecord' referenced from scope '', but it is not defined
If I try anonymous object like new {} instead of new WatchedUrlQueue then InsertIntoSelect() throws error:
'watched_url_record"."user_auth_custom_id' is not a property of 'WatchedUrlQueue'
I have looked in documentation and can see SelectMulti() method but I don't think that is suitable as it will involve me creating a tuple list to combine into the new object. The passed list can be quite large so I just want to send the correct SQL statement to PostgreSQL which would be along lines of:
insert into watched_url_queue (watched_url_record_id, url, domain_key, target_domain_record_id, target_domain_key, create_date, tries, defer_until, user_auth_custom_id)
select wur.id watched_url_record_id,
wur.url url,
wur.domain_key,
wur.target_domain_record_id,
tdr.domain_key,
'{DateTime.UtcNow:MM/dd/yyyy H:mm:ss zzz}' create_date,
0 tries,
null defer_until,
wur.user_auth_custom_id
from watched_url_record wur
join target_domain_record tdr on wur.target_domain_record_id = tdr.id
where wur.id in (323,3213123,312312,356456)
on conflict do nothing ;
I currently have a lot of similar type queries in my app and it is causing extra work maintaining them, would be really nice to be able to have them use fluent api without reducing performance. Is this possible?
Custom select expression can't be a typed projection (i.e. x => new MyType { ... }), i.e. you'd need to use an anonymous type expression (i.e. new { ... }) which captures your query's Custom SELECT Projection Expression.
You'll also need to put your JOIN expressions directly after FROM (as done in SQL) which tells OrmLite it needs to fully qualify subsequent column expressions like Id which would otherwise be ambiguous.
I've resolved an issue with field resolution of custom select expressions in this commit where your query should now work as expected:
var q = db.From<WatchedUrlRecord>()
.Join<TargetDomainRecord>((w, t) => w.TargetDomainRecordId == t.Id)
.Where(x => Sql.In(x.Id, ids))
.Select<WatchedUrlRecord, TargetDomainRecord>((w, t) => new {
UserAuthCustomId = w.UserAuthCustomId,
DomainKey = w.DomainKey,
CreateDate = DateTime.UtcNow,
DeferUntil = (DateTime?) null,
FirstScan = firstScan,
TargetDomainKey = t.DomainKey,
Tries = 0,
TargetDomainRecordId = w.TargetDomainRecordId,
Url = w.Url,
WatchedUrlRecordId = w.Id
});
var inserted = db.InsertIntoSelect<WatchedUrlQueue>(q, dbCmd=>dbCmd.OnConflictIgnore());
This change is available from v5.10.5 that's now available on MyGet.

Servicestack Ormlite generates invalid SQL query for custom select

I am using version 4.5.14 of Servicestack ormlite
here "InMaintenance" Property is ignored as it is not the "Network" table column in the database. I want to set the value of the InMaintenance property based on whether the "Enddate" column in the NetworkMain table has value or not.
Following is the code
but the above code generates the following SQL query for SelectExpression
as we can see there is no space between the not null condition in the above expression.
And FromExpression is as follows
I know that I can use the SQL query in the select but how to resolve this issue?
Thanks!
Amol
4.5.14 is several years old, but this generates valid SQL in the latest version of OrmLite. Here's a live demo on Gistlyn you can run:
OrmLiteUtils.PrintSql();
public class Network
{
[PrimaryKey]
public string Id { get; set; }
public string Name { get; set; }
[Ignore]
public bool InMaintenance { get; set; }
}
public class NetworkMain
{
[PrimaryKey]
public string Id { get; set; }
[ForeignKey(typeof(Network))]
public string NetworkId { get; set; }
public DateTime? EndDate { get; set; }
}
public class NetworkDTO
{
public string Id { get; set; }
public string Name { get; set; }
public bool InMaintenance { get; set; }
}
var q = db.From<Network>()
.LeftJoin<NetworkMain>()
.Select<Network, NetworkMain>((a, m) => new
{ a,
InMaintenance = m.NetworkId == a.Id && m.EndDate.HasValue ? "1" : "0"
}).OrderBy(x=>x.Name);
var results = db.Select<NetworkDTO>(q).ToList();
Which generates:
SELECT "Network"."Id", "Network"."Name", (CASE WHEN (("NetworkMain"."NetworkId"="Network"."Id")AND("NetworkMain"."EndDate" is not null)) THEN #0 ELSE #1 END) AS InMaintenance
FROM "Network" LEFT JOIN "NetworkMain" ON
("Network"."Id" = "NetworkMain"."NetworkId")
ORDER BY "Network"."Name"

SQLite.net: Query one single column

I have a model of the following form:
public class LanguageText
{
[PrimaryKey]
public int Id { get; set; }
public string de { get; set; }
public string en { get; set; }
public string ru { get; set; }
}
How can I query just one column by Id? I tried this:
SQL = "SELECT [de] from [LanguageText] WHERE [Id] = \"1\""
var p = App.Database.QueryAsync<LanguageText>(SQL).Result.First();
This will return one whole row of LanguageText in p, while I want the contents of the [de] row as string only.
How do I accomplish this?
As we found out
App.Database.ExecuteScalarAsync<string>(SQL).Result

ServiceStack AutoQuery - Anomaly When Using "?Fields="

We have noticed an anomaly when using "?Fields=" in version 4.0.55 (pre-release on MyGet).
We have an Employee table with three 1:1 relationships - EmployeeType, Department and Title:
public partial class Employee {
[PrimaryKey]
[AutoIncrement]
public int ID { get; set; }
[References(typeof(EmployeeType))]
public int EmployeeTypeID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
[References(typeof(Title))]
public int TitleID { get; set; }
.
.
.
}
public class EmployeeType {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
}
public class Department {
[PrimaryKey]
public int ID { get; set; }
public string Name { get; set; }
[Reference]
public List<Title> Titles { get; set; }
}
public class Title {
[PrimaryKey]
public int ID { get; set; }
[References(typeof(Department))]
public int DepartmentID { get; set; }
public string Name { get; set; }
}
The latest update to 4.0.55 allows related DTOs to be requested using ?Fields= on the query string like this:
/employees?fields=id,firstname,lastname,departmentid,department
Note that the "proper" way to request a related DTO (department) is to also request the foreign key field (departmentid, in this case).
We wondered if there was a way to return all of the Employee table fields and only selected related DTOs, so in testing we found that this request works:
/employees?fields=department
We get back all the Employee table fields plus the related Department DTO - with one strange thing - the Employee's ID field is populated with the Employee's TitleID values.
Specifying the foreign key field in the request fixes that anomaly:
/employees?fields=id,departmentid,department
but we lose all of the other Employee fields.
Is there a way that to get all of the Employee fields and selected related DTOs?
Here is our AutoQuery DTO:
[Route("/employees", "GET")]
public class FindEmployeesRequest : QueryDb<Employee>,
IJoin<Employee, EmployeeType>,
IJoin<Employee, Department>,
IJoin<Employee, Title> {
public int? ID { get; set; }
public int[] IDs { get; set; }
public string UserID { get; set; }
public string[] UserIDs { get; set; }
public int? EmployeeTypeID { get; set; }
public int[] EmployeeTypeIDs { get; set; }
public int? DepartmentID { get; set; }
public int[] DepartmentIDs { get; set; }
public int? TitleID { get; set; }
public int[] TitleIDs { get; set; }
public string LastNameStartsWith { get; set; }
public DateTime[] DateOfBirthBetween { get; set; }
public DateTime[] HireDateBetween { get; set; }
public bool? IsActive { get; set; }
[QueryDbField(Template = "(MONTH({Field}) = {Value})", Field = "DateOfBirth")]
public int? BirthMonth { get; set; }
[QueryDbField(Template = "(DAY({Field}) = {Value})", Field = "DateOfBirth")]
public int? BirthDay { get; set; }
[QueryDbField(Template = "(FirstName LIKE {Value} OR LastName LIKE {Value} OR PreferredName LIKE {Value})", ValueFormat = "%{0}%", Field = "ID")]
public string NameSearch { get; set; }
[QueryDbField(Template = "(FirstName LIKE {Value} OR LastName LIKE {Value} OR PreferredName LIKE {Value} OR Department.Name LIKE {Value} OR Title.Name LIKE {Value})", ValueFormat = "%{0}%", Field = "ID")]
public string BasicSearch { get; set; }
[QueryDbField(Template = "({Field} LIKE {Value})", Field = "EmployeeTypeName", ValueFormat = "%{0}%")]
public string EmployeeTypeSearch { get; set; }
[QueryDbField(Template = "({Field} LIKE {Value})", Field = "DepartmentName", ValueFormat = "%{0}%")]
public string DepartmentSearch { get; set; }
[QueryDbField(Template = "({Field} LIKE {Value})", Field = "TitleName", ValueFormat = "%{0}%")]
public string TitleSearch { get; set; }
}
Support for wildcard custom field lists was added in this commit where you can specify all fields of the primary or joined table by adding a .* suffix, e.g:
?fields=id,departmentid,department,employee.*
It essentially serves as a substitute placeholder which will be replace it with all fields in the specified table.
This change is available from v4.0.55 that's now available on MyGet.

ServiceStack.OrmLite - how to include field from foreign key lookup?

I'm trying out the ServiceStack MVC PowerPack, and am trying the included OrmLite ORM and am trying to get data from a table referenced by a foreign key without any idea how to do so.
In the OrmLite examples that use the Northwind database, for example, would it be possible to return a Shipper object that included the "ShipperTypeName" as a string looked up through the foreign key "ShipperTypeID"?
From http://www.servicestack.net/docs/ormlite/ormlite-overview, I'd like to add the ShipperName field to the Shipper class if possible:
[Alias("Shippers")]
public class Shipper : IHasId<int>
{
[AutoIncrement]
[Alias("ShipperID")]
public int Id { get; set; }
[Required]
[Index(Unique = true)]
[StringLength(40)]
public string CompanyName { get; set; }
[StringLength(24)]
public string Phone { get; set; }
[References(typeof(ShipperType))]
public int ShipperTypeId { get; set; }
}
[Alias("ShipperTypes")]
public class ShipperType : IHasId<int>
{
[AutoIncrement]
[Alias("ShipperTypeID")]
public int Id { get; set; }
[Required]
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set; }
}
To do this you would need to use Raw SQL containing all the fields you want and create a new Model that matches the SQL, so for this example you would do something like:
public class ShipperDetail
{
public int ShipperId { get; set; }
public string CompanyName { get; set; }
public string Phone { get; set; }
public string ShipperTypeName { get; set; }
}
var rows = dbCmd.Select<ShipperDetail>(
#"SELECT ShipperId, CompanyName, Phone, ST.Name as ShipperTypeName
FROM Shippers S INNER JOIN ShipperTypes ST
ON S.ShipperTypeId = ST.ShipperTypeId");
Console.WriteLine(rows.Dump());
Which would output the following:
[
{
ShipperId: 2,
CompanyName: Planes R Us,
Phone: 555-PLANES,
ShipperTypeName: Planes
},
{
ShipperId: 3,
CompanyName: We do everything!,
Phone: 555-UNICORNS,
ShipperTypeName: Planes
},
{
ShipperId: 4,
CompanyName: Trains R Us,
Phone: 666-TRAINS,
ShipperTypeName: Trains
}
]

Resources