views:

99

answers:

1

I am trying to create a new instance of a Customer entity in our application, and I am having a few problems. This entity has several navigational properties, each of which has their own nav. properties. For example, each Customer entity has an Address entity, and each Address entity has a Phone Number entity etc. I haven't figured out how to get the new data set for all of those entities. I've tried the following:

context.Customers newCustomer = context.Customers.CreateCustomer(...);
newCustomer.FirstName = firstNameTextBox.Text;
newCustomer.Address.Street = streetTextBox.Text;   // this is where the error is thrown

At this point, I get an "Object reference not set to an instance of an object" error because Address is null. I had originally assumed that creating the new customer entity would automatically create a new instance of each entity that it is related to, but this must not be the case. Can someone provide a code example of how this is supposed to work? Thanks.

A: 

First, I would be remiss if I didn't note that an address is a value type; it doesn't have identity, and should not be an entity. The Entity Framework supports such types via the complex types feature. Unfortunately, the Entity Framework designer has zero support for this (Edit: Fixed in VS 2010), so the only way to use the feature is to edit the EDMX manually. As it happens, Address is the type used in most of examples, see you might want to consider this.

Nevertheless, I will actually answer the question you asked.

The simple solution would be:

newCustomer.Address = new Address()
    {
        Street = streetTextBox.Text,
        // etc.
    };

However, since Address is really a value type (in other words, two customers with the exact same street address should probably point to the same Address object), you may want to try and select an existing Address object from the context before you just go and new up a new one.

newCustomer.Address = (from Addresses in context where ...).FirstOrDefault();
if (newCustomer.Address == null)
{
    newCustomer.Address = new Address()
        {
            Street = streetTextBox.Text,
            // etc.
        };
}
Craig Stuntz
Null coalescing operator is very good here: `custom.Address = (from a in db).FirstOrDefault() ?? new Address { Street = "street" };`
abatishchev