多个到多个插入

时间:2013-04-13 11:47:06

标签: c# wcf entity-framework many-to-many wcf-data-services

我有一个运行oData的WCF数据服务,并尝试将数据插入其中。我正在尝试从Windows 8客户端异步。

我的实体看起来像这样:

Customer 1 -> m CustomerAddress 1 <- m Address

我可以通过简单地调用AddObject方法并保存更改来插入地址或客户:

context.AddObject("Customer",new Customer { FirstName="foo" });
context.AddObject("Address",new Address { Street="bar" });
await context.SaveChangesBatch(); //a extension class that handels the BeginSaveChanges async calls as batch

我还可以在地址和客户之间添加关系

Customer customer=new Customer { FirstName="foo" };
Address orderAddress=new Address { Street="bar" };
CustomerAddress customerAddress = new CustomerAddress { Customer = customer, Address = orderAddress };
context.AddObject("Customer",customer);
context.AddObject("Address",orderAddress);
context.AddObject("CustomerAddress",customerAddress);
await context.SaveChangesBatch(); 

但是,我无法在上下文中添加第二个相关地址:

Address orderAddress=new Address { Street="bar" };
Address deliveryAddress=new Address { Street="bar2" };
CustomerAddress customerAddress = new CustomerAddress { Customer = customer, Address = orderAddress };
Customer customer=new Customer { FirstName="foo" };
CustomerAddress customerAddress = new CustomerAddress { Customer = customer, Address = deliveryAddress };
context.AddObject("Customer",customer);
context.AddObject("Address",orderAddress);
context.AddObject("Address",deliveryAddress);
context.AddObject("CustomerAddress",customerAddress);
context.AddObject("CustomerAddress",customerAddress2);
await context.SaveChangesBatch(); 

this post中,我读到了只需插入相关实体就可以了:

CustomerAddress customerAddress = new CustomerAddress { Customer = customer, Address = orderAddress };
CustomerAddress2 customerAddress = new CustomerAddress { Customer = customer, Address = deliveryAddress };
context.AddObject("CustomerAddress",customerAddress);
context.AddObject("CustomerAddress",customerAddress2);
await context.SaveChangesBatch(); //On save, it should automatically insert customer and order but it dosn't work :(

这将是完美的,但它不起作用。该错误显示forign键错误。我有什么设置错误吗?我的EF看起来像这样:

EF Model

我是否必须在foregin键属性上添加一些东西:(我正在使用模型第一个approch) enter image description here

作为附加节点:我使用的是Azure SQL数据库,因此不允许使用复合键:(

1 个答案:

答案 0 :(得分:0)

可能是我错了,但区别在于你引用的帖子中,MemberComments(在你的情况下是CustomerAddress) - 是集合:

 public virtual ICollection<MemberComment> MemberComments { get; set; }

添加项目时,不将它们添加到上下文中,而是添加到集合中:

  

上下文的 MemberComments 。新增(memberComment1)。 //还会添加member1   和comment1上下文。成员评论 .Add(memberComment2); // 也会   添加评论2

所以,在你的情况下,可能,它应该像

  

上下文的 your_defined_CustomerAddressesList 。新增(customerAddress)。   。上下文的 your_defined_CustomerAddressesList 。新增(customerAddress2);