建立实体关联(以Active Record模式为例)

  • 为了处理订单和订单明细的关系,我们需要创建与订单明细对应的实体:
public class OrderDetailInfo
{
    public ISimpleMapper<OrderDetailInfo> Mapper;
    public OrderDetailInfo()
    {
        this.Mapper = SimpleMapper.Inject(this, null);
    }

    public int? OrderDetailID { get; set; }
    public int? OrderID { get; set; }
    public string ItemCode { get; set; }
    public decimal? Price { get; set; }
}
  • 然后将OrderDetailInfo.OrderID做为外键关联到OrderInfo.OrderID字段:
public class OrderInfo
{
    public ISimpleMapper<OrderInfo> Mapper;
    public OrderInfo()
    {
        this.Mapper = SimpleMapper.Inject(this, null);
        //将OrderDate的默认查询条件由“等于”更改为“大于等于”
        this.Mapper.EntityFieldInfos["OrderDate"].SelectMethod = ESelectMethod.GreaterThan; 
    }
    //设置一对多关联
    public OrderDetailInfo OrderDetail
    {
        get { return new OrderDetailInfo { OrderID = this.OrderID }; }
    }

    #region 实体字段
    public int? OrderID { get; set; }
    public string OrderNo { get; set; }
    public string CustomerID { get; set; }
    public DateTime? OrderDate { get; set; }
    #endregion
}
  • 现在,查询2012-03-06日第一个订单,并显示订单明细:
var result = new OrderInfo { OrderDate = DateTime.Parse("2012-03-06") }.Mapper.First().OrderDetail.Mapper;
//输出数据:
//OrderDetailID OrderID ItemCode    Price
//1             2       iPhone4s    5999.0000 
//2             2       Kindle3     1299.0000
  • 让我们看看KylinORM生成的Sql语句:
SELECT TOP 1 * FROM [Order] WHERE [OrderDate]>@OrderDate
SELECT * FROM [OrderDetail] WHERE [OrderID]=@OrderID

下一页:多表连接查询

Last edited Oct 20, 2012 at 12:35 PM by gameboyLV, version 4

Comments

No comments yet.