I am trying to get identifiying relationships to work in Entity Framework so I can remove items from their collection using Remove.
I have created a test like:
public class OrderLine{
[Key, Column(Order = 0)]
public int OrderLineId { get; set; }
[Key, ForeignKey("Order"), Column(Order = 1)]
public int OrderId{ get; set; }
public virtual Order Order{ get; set; }
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public int Number { get; set; }}
When I attempt to add a OrderLine like:
var order=_orderRepository.Find(1);
var NewOrderLine= new OrderLine()
{
Number = 1,ProductId= 2
};
order.OrderLines.Add(NewOrderLine);
_orderRepository.InsertOrUpdate(order);
_orderRepository.Save();
I get the error
Cannot insert explicit value for identity column in table 'OrderLines' when IDENTITY_INSERT is set to OFF.
When I look at the table SQL has a primary key over OrderId and OrderLineId. Also only OrderLineId is set as identity. So it must be trying to insert a value but the only value it seems to be trying to insert is 0.
Any ideas I can do an insert to the table using:
INSERT INTO [OrderLines]
([ProductId ]
,[Number]
,[OrderId])
VALUES
(2
,1
,1)
I believe the exception means that one of the composite primary key columns in table OrderLines
is an autogenerated identity in the database (I guess the column OrderLineId
) but EF does send a value (0
because you don't specify the property when you create the new OrderLine
) for this column in the INSERT statement to the database because the property is not marked as identity in the EF model. By default (= IDENTITY_INSERT
is OFF
) SQL Server does not allow to insert a value into an identity column explicitly.
Indeed in your mapping the key columns are not identities because by default in a composite key no property is an identity.
I think, the solution is to either turn off the identity specification in the database or mark the property as identity in the model:
public class OrderLine
{
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OrderLineId { get; set; }
[Key, ForeignKey("Order"), Column(Order = 1)]
public int OrderId { get; set; }
public virtual Order Order { get; set; }
// ...
}
DatabaseGeneratedOption.Identity
means that EF expects that the column value is generated in the database and therefore does not send the value to the DB when you try to insert an new entity.
来源:https://stackoverflow.com/questions/11051155/identifying-relationship-and-inserting-child-entities-causes-cannot-insert-expl