The property 'myFk' on entity type 'Order' has a temporary value

c# entity-framework-core

Question

I have a one-to-many relationship with an order and some orderlines.

When updating the runtime from 2.0.? to NetCore 2.2.7 I have started to get this message:

System.InvalidOperationException: The property 'OrderId' on entity type 'OrderLineDto' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

Did anything change when updating, and what exactly is this error? In the OrderlineDto I do have an OrderId, but I have never done anything to maintain it, nor would I assume I should.

Simplified my code looks like this:

Order o = new OrderDto() {Foo = "Foo"};
o.Lines.Add(new OrderlineDto(whatever) {Bar = "Bar"});
_db.Orders.Add(o);
_db.SaveChanges();

OrderlineDto is database first and looks like this:

[Key]
[Column("Id_pk")]
public int Pk { get; set; }
public int OrderId { get; set; }
public virtual OrderDto Order { get; set; }

This also seems to still work on some computers, but not on others. So it could be a bad installation or something, but if a codechange could be made that solves it explicit then I am also interested in that.

1
0
11/4/2019 12:12:10 PM

Accepted Answer

For some reason the problem was a wrong ChangeTracker. My solution was to manually detatch everything on every save. I'll leave the solution here if others search for something similar.

var changedEntriesCopy = _db.ChangeTracker.Entries().ToList();
await _db.SaveChangesAsync();
foreach (var entry in changedEntriesCopy)
    entry.State = EntityState.Detached;
0
11/6/2019 2:35:48 PM

Popular Answer

it seems like the entity framework doesn't recognize the one-to-many relationship you can try to add this code on your OnModelCreating()

 modelBuilder.Entity<OrderlineDto>()
      .HasOne(ol => ol.OrderDto)
      .WithMany()
      .HasForeignKey(p => p.OrderId);

then add migration and check if there is any updates on database



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow