简体   繁体   中英

Db.SaveChanges Not Assigning Primary Key ID After Insert - Code First Entity Framework

I have a really weird situation with one class specifically. Upon adding the class to the DbContext to insert into the database and calling Db.SaveChanges code first/ef is not assigning the primary key id back to the class.

It's really odd, I've never encountered this before and I can't seem to find any solutions online.

Here is what the code looks like currently...

Invoice Code First Class

[Table("invoice")]
public class Invoice
{
    [Key]
    [Column("invoice_id")]
    public int InvoiceId { get; set; }

    [Column("invoice_credit_card_payment_id")]
    public int InvoiceCreditCardPaymentId { get; set; }

    [Column("batch_id")]
    public int BatchId { get; set; }

    [Column("customer_id")]
    public int CustomerId { get; set; }

    etc.....
}

Code to Insert Invoice into Database

var invoice = new Invoice()
{
    BatchId = 0,
    Memo = "",
    PayDateTime = DateTime.Now,
    QuickbooksAccountName = "",
    QuickbooksId = "",
    Terms = "",
    etc....
};

DbContext.Current.Invoices.Add(invoice);
//Invoice record does insert successfully!
DbContext.Current.SaveChanges();

//This returns ZERO
var id = invoice.InvoiceId;

Additional Notes

As a side note the invoice record is successfully inserted into the database, however, the ID is not assigned back to the invoice object.

Another note - I have around 30 other code first classes that work just fine when doing inserts and getting ID's - it's just this one that is giving me issues for some weird reason.

Per jwatts1980 Recommendation

I updated the invoice class to reflect this

[Key]
[Column("invoice_id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InvoiceId { get; set; }

This did not solve the problem immediately, however it did reveal a new error upon insert:

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'invoice_id'

I found a stackoverflow answer here which lead me to find some foreign key attributes I had setup on the invoice class:

[ForeignKey("InvoiceId")]
public ICollection<InvoiceOrder> InvoiceOrders { get; set; }

[ForeignKey("InvoiceId")]
public InvoiceCreditCardPayment InvoiceCreditCardPayment { get; set; }

Removing the ForeignKey attributes above seemed to solve the problem so far. I can't say that the it won't cause an other errors, however so far everything appears to be working well.

This attribute might help

[Key]
[Column("invoice_id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InvoiceId { get; set; }

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