Click here to Skip to main content
14,970,493 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
currently I am learning ASP.NET and I stuck on storing data to multiple tables. Database model is shown bellow:

http://s3.postimg.org/saq19m81f/Untitled.png[^]

What I want to achieve is when I add new contact to Contact table to get last insert ID and automatically insert data for tables Phone/Tag/Email (if there is some data for that tables). Is there a chance to do it in single query or do I need to run fresh query for each table? I am using ASP.NET MVC with Entity Framework (auto-generated) model.

Here is model that is used in Controller:

public partial class Contact
    {
        public Contact()
        {
            this.Emails1 = new HashSet<Email>();
            this.Phones1 = new HashSet<Phone>();
            this.Tags1 = new HashSet<Tag>();
        }

        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string address { get; set; }
        public string city { get; set; }
        public Nullable<byte> bookmarked { get; set; }
        public string notes { get; set; }

        public virtual ICollection<Email> Emails1 { get; set; }
        public virtual ICollection<Phone> Phones1 { get; set; }
        public virtual ICollection<Tag> Tags1 { get; set; }
    }
}


Here is model For Phone/Tags/Email tables (it's same with different name in one column)

public string AddContact(Contact contact)
        {
            if (contact != null)
            {

                db.Contacts.Add(contact);
                db.SaveChanges();
                    return "Contact Added";
            }
            else
            {
                return "Invalid Record";
            }
        }
Posted

1 solution

Entity Framework will do it for you, in multiple queries. You just have to build the object graph, adding each entity to their respective tables and navigation collections, then call SaveChanges on the context.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900