开发者

Entity Framework: Add new object and link to 2nd new object via navigational property

I have a scenario where I'm creating two new objects which are linked via a navigational property (foreign key), eg:

            ClientAccount client = new ClientAccount {
                ......
                AccountTypeId = 1
            };

            ClientEmailAddress email =开发者_运维百科 new ClientEmailAddress {
                ClientId = client.Id,
                EmailAddress = "test@test.com"
            };

           client.FkClientEmailAddresses.Add(email);

When I try to save though, via dbContext.SaveChanges();, I get an exception:

Cannot add or update a child row: a foreign key constraint fails (`test`.`client_email_addresses`, CONSTRAINT `FK_client_email_addresses_client_accounts` FOREIGN KEY (`client_id`) REFERENCES `client_accounts` (`client_account_id`))

I believe this is because the ClientAccount object does not have an ID at the time I'm assigning it to the ClientEmailAdresss object.

Can anyone confirm whether what I'm trying to do is possible? I'd rather not have multiple .SaveChanges calls.


You should use this instead:

        ClientAccount client = new ClientAccount {
            ......
            AccountTypeId = 1
        };

        ClientEmailAddress email = new ClientEmailAddress {
            Client = client,
            EmailAddress = "test@test.com"
        };

       client.FkClientEmailAddresses.Add(email);

This will allow EF to track reference between the assigned client and email address and once real id is returned from the database EF should correctly set FK in your email address entity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜