1

I have two objects in the database and the relationship between them as below. I follow the instruction here to create a new Contact and Account which are a new principal and dependent object respectively. Below is my code.

This works fine one way when newContact and newAccount are created. The business_contact_uid and business_address_uid show the uid of the newContact. However, the aid of newContact is null. <-- I want it to show the uid of the newAccount as well.

So what I understand is that I created newContact as a principal object and newAccount as a dependent one. Is there anyway to let EF know that aid relationship as well when they are created?

using (var frontendDb = new salon_database_test())
{
     var newContact = new Contact
     {
         first_name = model.FirstName,
         last_name = model.LastName,
         email = model.Email,
     };
     frontendDb.contacts.Add(newContact);

     var newAccount = new Account
     {
         name = model.BusinessName,
         country_id = model.Country,
         BusinessContact = newContact,
         BusinessAddress = newContact
     };
     frontendDb.accounts.Add(newAccount);

     frontendDb.SaveChanges();
}

enter image description here

Below are the Contact class and Account class

public class Contact
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order=1)]
    public int uid { get; set; }

    [Column(Order = 2)]
    public int? aid { get; set; }
    [IgnoreDataMember, ForeignKey("aid")]
    public virtual Account account_owner { get; set; }

    //..others..
}

public class Account
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Column(Order=1)]
    public int uid { get; set; }

    // Address of the business 
    public int? business_address_uid { get; set; }
    [IgnoreDataMember, ForeignKey("business_address_uid")]
    public virtual Contact BusinessAddress { get; set; }

    // Contact details for the main contact of the account (business owner)
    public int? business_contact_uid { get; set; }
    [IgnoreDataMember, ForeignKey("business_contact_uid")]
    public virtual Contact BusinessContact { get; set; }
}
Hien Tran
  • 1,443
  • 2
  • 12
  • 19

0 Answers0