Yaroslav Veremenko
Yaroslav Veremenko

Reputation: 747

How to insert new row with complex key when one column is identity and other is not?

I have a model for orders. They both are keys and cannot be duplicated. I set OrderId as Identity in Map class.

class Order {
    public int OrderId {get;set;}
    public int OrderNumber {get;set;}
    ...    
}

Now I need to generate new OrderNumber to insert the row. I know in SQL I can wrap into transaction and do MAX(OrderNumber) + 1, but how can I do it in Entity Framework?

Upvotes: 1

Views: 58

Answers (1)

Rob Lyndon
Rob Lyndon

Reputation: 12681

You can make OrderNumber an identity column:

class Order
{
    public int OrderId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int OrderNumber { get; set; }
}

By convention, Entity Framework will recognise that OrderId is a primary key; however, it will not automatically be an identity column, so you need so add the DatabaseGenerated(DatabaseGeneratedOption.Identity) to OrderId is you want it to be auto-incrementing.

However, if you don't want to change your database, you can wrap your insertion in a transaction:

using (var transaction = modelContext.BeginTransaction())
{
    var newOrderNumber = modelContext.Orders.Max(o => o.OrderNumber) + 1;
    var newOrder = new Order { OrderNumber = newOrderNumber };
    ...
    transaction.Commit();
}

And then assign this value plus one to your new Order object.

Upvotes: 1

Related Questions