我正在尝试使用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; }
}
Run Code Online (Sandbox Code Playgroud)
myt*_*thz 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());
Run Code Online (Sandbox Code Playgroud)
哪个会输出以下内容:
[
{
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
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7669 次 |
| 最近记录: |