4

我正在试用 ServiceStack MVC PowerPack,并正在尝试包含的 OrmLite ORM,并正在尝试从外键引用的表中获取数据,但不知道该怎么做。

例如,在使用 Northwind 数据库的 OrmLite 示例中,是否可以返回一个包含“ShipperTypeName”作为通过外键“ShipperTypeID”查找的字符串的 Shipper 对象?

http://www.servicestack.net/docs/ormlite/ormlite-overview,如果可能,我想将 ShipperName 字段添加到 Shipper 类:

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

1 回答 1

10

为此,您需要使用包含您想要的所有字段的原始 SQL 并创建一个与 SQL 匹配的新模型,因此对于此示例,您将执行以下操作:

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());

这将输出以下内容:

[
    {
        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
    }
]
于 2011-12-23T15:42:57.750 回答