Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

servicestack

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; }
}
like image 550
Dennis Ward Avatar asked Dec 28 '22 08:12

Dennis Ward


1 Answers

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
    }
]
like image 129
mythz Avatar answered Jan 31 '23 09:01

mythz