EF Code First - 具有子实体的序列号

时间:2017-05-17 05:04:40

标签: c# asp.net entity-framework

将EF 6.X与Asp.Net Web应用程序一起使用。

考虑以下父母子女关系。 订单实体可以有一个或多个OrderLines。 在OrderLine实体中,我希望有一个序列列。

enter image description here

如上图所示,序列应从每个订单的1开始。 我怎样才能通过EF实现这一目标?期待一个简单的解决方案来解决这个问题。

1 个答案:

答案 0 :(得分:1)

无法自动执行此操作。订单行的数据模型需要属性SequenceNo。更高级别的抽象Data Access Layer?必须确保无论何时“订单线”都是如此。已添加正确的SequenceNo已填充。

public class Order
{
    // primary Key
    public int Id {get; set;}

    // an Order has a collection of OrderLines:
    public virtual ICollection<OrderLine> OrderLines {get; set;}
    ...
}

public class OrderLine
{
    public int Id {get; set;} // primary key

    // foreign key to owning Order
    public int OrderId {get; set;}
    public virtual Order Order {get; set;}

    public int OrderLineNo {get; set;}
    public int SequenceNo {get; set;}
    ...
}

public MyDbContrext : DbContext
{
    public DbSet<Order> Orders {get; set;}
    public DbSet<OrderLine> OrderLines {get; set;}
    ...
}

更高的抽象级别

public int IntroduceOrder(...)
{
    using (MyDbContext dbContext = ...)
    {
        Order orderToAdd = new Order()
        {
            ...
        }
        var addedOrder = dbContext.Orders.Add(orderToAdd);
        dbContext.SaveChanges();
        return addedOrder.Id;
    }
}

public OrderLine AddOrderLine(int orderId, ...)
{
    using (MyDbContext dbContext = ...)
    {
        // get the sequenceNo from the orderline of the order with orderId
        // with the highest sequenceNo
        // = first element when ordered descending
        int highestSeqenceNo = dbContext.OrderLines
            .Where(orderLine => orderLine.OrderId == orderId)
            .Select(orderLine => orderLine.SequenceNo)
            .OrderByDescending(sequenceNo => sequenceNo)
            .FirstOrDefault();
       // if there were no order lines yet, highestSequenceNo has value 0

       const int sequenceNoFirstOrderLine = 1;
       // or whatever value you want as sequenceNo for the first OrderLine

       int nextSequenceNo = (highestSequenceNo == 0) ? 
           sequenceNoFirstOrderLine :
           highestSequenceNo + 1;
       OrderLine orderLineToAdd = new OrderLine()
       {
           ...
           SequenceNo = nextSequenceNo,
       };
       var addedOrderLine = dbContext.Orders.Add(orderLineToAdd);
       dbContext.SaveChanges();
       return addedOrderLine;
    }
}