简体   繁体   中英

EF Code First - Having Sequence Number for child entities

Using EF 6.X with Asp.Net web application.

Consider below parent child relationship. A Order Entity can have one or more OrderLines. In the OrderLine entity I would like to have a sequence column.

在此处输入图片说明

As shown in the above image, the sequence should be start from 1 for each Orders. How can I achieve this through EF? Expecting a simple solution to solve this.

It is not possible to do this automatically. Your data model of the order line will need a property SequenceNo . Higher levels of abstraction Data Access Layer? will have to make sure that whenever an 'OrderLine' is added the correct SequenceNo is filled.

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;}
    ...
}

Higher Level Of abstraction

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM