Thomas Koelle
Thomas Koelle

Reputation: 3742

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

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.

Upvotes: 0

Views: 1901

Answers (2)

Thomas Koelle
Thomas Koelle

Reputation: 3742

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;

Upvotes: 0

Besher Tobeh
Besher Tobeh

Reputation: 249

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

Upvotes: 1

Related Questions