-1

I am following this tutorial to make a one-to-one relationship but with no avail. http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

here is my quick mock up

public class Information
{
    public int InformationId { get; set; }

    public string Thing1 {get; set;}
    public string Thing2 { get; set;}

    public ICollection<Item> Items { get; set; }
    public Account Account { get; set; }
}

public class Account
{
    [Key, ForeignKey("Information")]
    public int InformationId { get; set; }

    public string Thing1 { get; set; }

    public Information Information { get; set; }
}

and I execute this against it

var information = new List<Information>{
            new Information(){
                Thing1 = "this",Thing2="that"
            }
        };
        information.ForEach(s => context.Information.Add(s));
        context.SaveChanges();

        var account = new List<Account>{
            new Account(){Thing1="one"}
        };
        account.ForEach(s => context.Accounts.Add(s));
        context.SaveChanges();

it errors with this

{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Account_dbo.Information_InformationId\". The conflict occurred in database \"TestEF\", table \"dbo.Information\", column 'InformationId'.\r\nThe statement has been terminated."}
Mark Hollas
  • 1,107
  • 1
  • 16
  • 44
  • save account first, then information – Mir Gulam Sarwar Feb 16 '16 at 05:17
  • thanks, that prevents error, however it seems only 'information' arrives in the database – Mark Hollas Feb 16 '16 at 05:28
  • when saving account first, then information the error was not thrown. however when looking at the database tables, there was a new record for 'information' but no record for 'account' – Mark Hollas Feb 16 '16 at 05:38
  • Thanks! After getting no error doing it the way you suggested, I realized the problem was only with how I was saving the entities, not with the association. Cheers – Mark Hollas Feb 16 '16 at 05:54

1 Answers1

0

save account first, then information

var account = new List<Account>{
            new Account(){Thing1="one"}
        };
        account.ForEach(s => context.Accounts.Add(s));
        context.SaveChanges();

var information = new List<Information>{
            new Information(){
                Thing1 = "this",Thing2="that"
            }
        };
        information.ForEach(s => context.Information.Add(s));
        context.SaveChanges();
Mir Gulam Sarwar
  • 2,588
  • 2
  • 25
  • 39