0

我正在尝试在我们的应用程序中创建客户实体的新实例,但遇到了一些问题。这个实体有几个导航属性,每个都有自己的导航。特性。例如,每个客户实体都有一个地址实体,每个地址实体都有一个电话号码实体等。我还没有弄清楚如何为所有这些实体获取新数据集。我尝试了以下方法:

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

此时,我收到“对象引用未设置为对象的实例”错误,因为地址为空。我最初假设创建新的客户实体会自动为与之相关的每个实体创建一个新实例,但事实并非如此。有人可以提供一个代码示例来说明这应该如何工作吗?谢谢。

4

1 回答 1

1

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.
        };
}
于 2009-02-04T16:50:04.220 回答