Reputation: 9607
Assume we have an Customer
object with collection of Payments
.
Initialization:
var dataContext = new TestDataContext();
dataContext.Customers.InsertOnSubmit(new Customer { Id = 1, Name = "Customer1" });
dataContext.SubmitChanges();
var customer = dataContext.Customers.Where(c => c.Id == 1).First();
First case:
customer.Payments.Add(new Payment { Amount = 100, CustomerId = customer.Id });
dataContext.SubmitChanges();
var count = dataContext.Payments.Count(); // count == 0
Second case:
dataContext.Payments.InsertOnSubmit(new Payment { Amount = 100, Customer = customer });
dataContext.SubmitChanges();
var count = dataContext.Payments.Count(); // count == 1
Third case (combined):
customer.Payments.Add(new Payment { Amount = 100, CustomerId = customer.Id });
dataContext.Payments.InsertOnSubmit(new Payment { Amount = 100, Customer = customer });
dataContext.SubmitChanges();
var count = dataContext.Payments.Count(); // count == 2 (!)
I assume that InsertOnSubmit
somehow notifies the DataContext
object about changes. But just wondered why it's not notified in the first case?
P.S. I am using SQL CE for Windows Phone.
Upvotes: 0
Views: 179
Reputation: 625
Have you tried setting the customer reference to Payment.Customer property in the first case?
E.g. customer.Payments.Add(new Payment { Amount = 100, Customer = customer });
I normally wouldn't set IDs explicitly, but make use of the ORM and establish proper relationships between entities.
Upvotes: 3