添加新项目并将其保存到集合中

时间:2011-12-17 17:10:03

标签: windows-phone-7

假设我们有一个Customer对象,其集合为Payments

初​​始化:

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();

第一种情况:

customer.Payments.Add(new Payment { Amount = 100, CustomerId = customer.Id });
dataContext.SubmitChanges();
var count = dataContext.Payments.Count(); // count == 0

第二种情况:

dataContext.Payments.InsertOnSubmit(new Payment { Amount = 100, Customer = customer });
dataContext.SubmitChanges();
var count = dataContext.Payments.Count(); // count == 1

第三种情况(合并):

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 (!)

我假设InsertOnSubmit以某种方式通知DataContext对象有关更改。但只是想知道为什么在第一种情况下没有通知它?

P.S。我正在使用SQL CE for Windows Phone。

1 个答案:

答案 0 :(得分:3)

您是否尝试在第一种情况下将客户参考设置为Payment.Customer属性?

E.g。 customer.Payments.Add(new Payment { Amount = 100, Customer = customer });

我通常不会明确设置ID,但会使用ORM并在实体之间建立适当的关系。

相关问题