在单个查询中将数据插入多个表

在单个查询中将数据插入多个表

本文介绍了在单个查询中将数据插入多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在学习ASP.NET,我坚持将数据存储到多个表中。数据库模型如下所示:



[]



我想要实现的是当我向Contact表添加新联系人以获取最后一个插入ID并自动插入表Phone / Tag / Email(如果有那些表的数据)。是否有机会在单个查询中执行此操作,还是需要为每个表运行新查询?我正在使用ASP.NET MVC和Entity Framework(自动生成)模型。



这是控制器中使用的模型:



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";
            }
        }

推荐答案


这篇关于在单个查询中将数据插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:40