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

偶尔善良 提交于 2019-12-28 12:43:22

问题


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; }
}

回答1:


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
    }
]


来源:https://stackoverflow.com/questions/8616516/servicestack-ormlite-how-to-include-field-from-foreign-key-lookup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!