Reputation: 1897
Simple example:
public class Order
{
public int OrderId { get; set; }
[MaxLength(128)]
public string OrderNo { get; set; }
public virtual List<Consigment> Consignments { get; set; }
}
public class Consigment
{
[Key]
public int ConsigmentId { get; set; }
public Guid Identifier { get; set; }
public int OrderId { get; set; }
public virtual Order Order { get; set; }
}
Now, What i want to do:
[...]
Order SomeOrder = GetOrdersBlahBlah();
Consigment consigment= new Consigment();
consigment.Identifier = Guid.NewGuid();
consigment.Order = SomeOrder;
_context.Orders.AddOrUpdate(SomeOrder);
_context.SaveChanges();
When i'm saving, no Consignment is saved to DB, and is not visible in consignments collection of order. How can I achieve this?
Upvotes: 0
Views: 151
Reputation: 16723
Your issue is that you are creating your consignment here:
Consigment consigment= new Consigment();
But you don't do anything with it. It just sits there, taking up space in memory, until your function goes out of scope.
You might think that the following makes the Entity Framework context aware of your consignment:
consigment.Order = SomeOrder;
_context.Orders.AddOrUpdate(SomeOrder);
But that's incorrect. Sure, consignment
knows about SomeOrder
, but SomeOrder
doesn't know anything about consignment
, and that's the one you are enrolling into the Entity Framework context.
You need to make the EF context aware of you consignment
variable, either by this:
SomeOrder.Consignments.Add(consignment);
or this:
_context.Consignments.Add(consignment);
Upvotes: 1