17

I'm using object and collection Initializers in the program and thinking how to get the example below.

Orders.Add(new Order() { id = 123, date = new datetime(2012,03,26) items = new OrderItems() { lineid = 1, quantity = 3, order = ?? // want to assign to current order. } } 

How can I assign the newly created order to the order item?

5
  • You might want to just add the OrderItems collection first and then assign the order. Or you might be okay with a one-way relationship. Commented Mar 26, 2012 at 19:10
  • 1
    Seems kind of odd from a modeling perspective. Why does an OrderItem contain an Order? I would think that the Order is the aggregate root and contains items with additional context about those items (OrderItems). But those items don't really need to know anything about the order. Commented Mar 26, 2012 at 19:11
  • As a workaround, you can make the setter for items assign the property transparently, although that won't work for OrderItems added to the collection later. Commented Mar 26, 2012 at 19:13
  • @David It could be an artifact of an ORM being used. Most people don't go through the bother of hiding the foreign key from children to parents in a 1:N relationship in the mapping; if the property is there already, it's better to keep it set to the right value for the sake of consistency. (Not ideal from a design POV, but there you go.) Commented Mar 26, 2012 at 19:16
  • Yes, it is existing semantic model I would like to keep them consistent. Commented Mar 26, 2012 at 19:22

2 Answers 2

13

What you're trying to here isn't possible. You can't refer to the object being constructed from within an object initializer body. You will need to break this up into a set of separate steps

var local = new Order() { id = 123, date = new datetime(2012, 03, 26); }; local.items = new OrderItems() { lineid = 1; quantity = 3; order = local; }; Orders.Add(local); 
Sign up to request clarification or add additional context in comments.

Comments

2

If Order.items is a property, you can put something like this in the property setter

public class Order { private OrderItems _items; public OrderItems items { get { return _items; } set { _items = value _items.order = this } } } 

Then you can just take the order out of the initializer:

Orders.Add(new Order() { id = 123, date = new datetime(2012,03,26) items = new OrderItems() { lineid = 1, quantity = 3, } } 

2 Comments

Thanks, It might be the solution to the example but I'm asking if there is any way during object initializer.
@laptop, I realize that. As JaredPar mentioned, what you were hoping to do per your example wasn't possible, so this was the best workaround without building each element separately as Jared suggested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.