EF 4 Code First - Help with model design RRS feed

  • Question

  • Hi,

    I am trying out EF and Code First approach

    I have an Account model which looks like

    public class Account
       public virtual int AccountID {get; set;}
       public virtual string AccountName {get; set;}
       public virtual Account ParentAccount {get; set;}
       public virtual Contact AccountOwner {get; set}

    Contact class is a simple class

    public class Contact
       public virtual int ContactID {get; set;}
       public virtual string ContactName {get; set;}

    Now I have no idea how to add IDs to the account class.

    Suppose I have set up the context correctly, what modifications are needed to the Account class so that

    1. I can add an Account as the parent of another Account

    2. I can access the ParentAccount of a particular Account

    3. I can access the AccountOwner of a particular Account

    I am new to this. Any help would be appreciated

    Sunday, January 6, 2013 8:17 AM


  • Hi Vive,

    Welcome to the MSDN forum.

    Please check the following code:

        public class Account
            public Int32 AccountID { get; set; }
            public String AccountName { get; set; }
            public virtual Account ParentAccount { get; set; }
            public virtual Contact AccountOwner { get; set; }
        public class Contact
            public Int32 ContactID { get; set; }
            public String ContactName { get; set; }
            public virtual ICollection<Account> Accounts { get; set; }
        public class tstContext : DbContext
            public DbSet<Account> Accounts { get; set; }
            public DbSet<Contact> Contacts { get; set; }
        class Program
            static void Main(string[] args)
                using (var context = new tstContext())
                    Contact contact = new Contact { ContactName = "Alex", Accounts = new List<Account>() };
                    Account child = new Account { AccountName = "Child" };
                    Account parent = new Account { AccountName = "Parent" };
                    child.ParentAccount = parent;//Add an account as the parent of another account.
                    child.ParentAccount.AccountName = "Alexander";//Acess parent account of a particular account.
                    child.AccountOwner = contact;//Access the account owner of a particular account.
                    parent.AccountOwner = contact;

    If you have any problem, please feel free to let me know.

    Good day.

    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, January 7, 2013 7:41 AM