gpt4 book ai didi

ServiceStack.OrmLite - 如何从外键查找中包含字段?

转载 作者:行者123 更新时间:2023-12-03 11:10:07 25 4
gpt4 key购买 nike

我正在尝试 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; }
}

最佳答案

为此,您需要使用包含您想要的所有字段的原始 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
}
]

关于ServiceStack.OrmLite - 如何从外键查找中包含字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com