I am using Entity Framework 4 with a POCO code generation template from Microsoft downloaded from Visual Studio Gallery. I also leave the default option "Include foreign keys in the model", selected when generating the EF-model from the database.
I was able to reproduce this problem with a very simple model, only two tables / classes in an optional one-to-many relationship. In this case, I use the address and identity. A person can have one or zero address, and the address can have zero for many people.
The tables look like this:
CREATE TABLE [dbo].[Person](
[PersonID] [uniqueidentifier] NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[AddressID] [uniqueidentifier] NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ([PersonID] ASC )
CREATE TABLE [dbo].[Address](
[AddressID] [uniqueidentifier] NOT NULL,
[Street1] [nvarchar](50) NOT NULL,
[Street2] [nvarchar](50) NULL,
[City] [nvarchar](50) NOT NULL,
[State] [char](2) NOT NULL,
[Country] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([AddressID] ASC)
ALTER TABLE [dbo].[Person] WITH CHECK ADD CONSTRAINT [FK_Person_Address]
FOREIGN KEY([AddressID])
REFERENCES [dbo].[Address] ([AddressID])
When I try to create an Address object and add it to an existing object, the Person pulled from the database, I get a null reference exception:
TestPOCOEntities ctx = new TestPOCOEntities();
var person = ctx.People.FirstOrDefault(p => p.PersonID == new Guid("58AD37B4-1EBE-4649-940C-A141732C9901"));
var addr = new Address {AddressID = Guid.NewGuid(), Street1 = "123 Main St"};
person.Address = addr;
ctx.SaveChanges();
, , Person AddressID. ( , System.Data.Objects.EntityEntry.FixupEntityReferenceByForeignKey(EntityReference reference).)
, EF POCO. , POCO, " " .
, :
var addr = new Address {AddressID = Guid.NewGuid(), Street1 = "123 Main St"};
ctx.Addresses.AddObject(addr);
person.Address = addr;
, POCO . ? - ? - ?