我正在尝试使用ServiceStack MVC PowerPack,我正在尝试使用包含的OrmLite ORM,并尝试从外键引用的表中获取数据,而不知道如何操作。
例如,在使用Northwind数据库的OrmLite示例中,是否可以将包含“ShipperTypeName”的Shipper对象作为通过外键“ShipperTypeID”查找的字符串返回?
从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; }
}
答案 0 :(得分:10)
要执行此操作,您需要使用包含所需字段的Raw 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
}
]