0

我有一个运行 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(); 

这篇文章中,我了解到只需像这样插入相关实体就足够了:

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 :(

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

英孚模型

我是否必须在foregin key properties上添加一些东西:(我使用的是模型优先方法) 在此处输入图像描述

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

4

1 回答 1

0

可能是我错了,但不同的是,在您引用的帖子中,MemberComments(在您的情况下 - CustomerAddress) - 是集合:

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

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

语境。会员评论 .Add(memberComment1) ; // 还将添加 member1 和 comment1 上下文。会员评论 .Add(memberComment2) ; // 也会添加comment2

所以,在你的情况下,可能应该是这样的

语境。your_defined_CustomerAddressesList .add(customerAddress); 语境。your_defined_CustomerAddressesList .add(customerAddress2);

于 2013-04-14T04:36:18.440 回答