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

我想要实现的是当我将新联系人添加到 Contact 表以获取最后一个插入 ID 并自动插入表 Phone/Tag/Email 的数据(如果该表有一些数据)。是否有机会在单个查询中执行此操作,还是需要为每个表运行新查询?

这是 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; }
    }
}

这是电话/标签/电子邮件标签的模型(在一列中具有不同的名称)

public partial class Email
    {
        public int id { get; set; }
        public int id_contact { get; set; }
        public string email1 { get; set; }

        public virtual Contact Contact1 { get; set; }
    }

这是将新行广告到数据库的 Controller 类:

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

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

最佳答案

您的联系人对象包含电子邮件、电话和标签的集合,因此在您调用 db.SaveChanges() 之前,您可以将它们添加到您的联系人集合中。

public string AddContact(Contact contact)
{
    if (contact != null)
    {
        db.Contacts.Add(contact);

        contact.Emails1.Add(new Email { Email1 = "email@email.com"})
        contact.Emails1.Add(new Email { Email1 = "email2@email.com"})

        contact.Phones1.Add(new Phone1 { PhoneNumber = "1234516123"})

        db.SaveChanges();
        return "Contact Added";
    }
    else
    {
            return "Invalid Record";
    }
}

只要确保您的外键引用设置正确,并且 Contact 对象有一个标识列,如果它将是一个新联系人。

关于c# - 在单个查询中将数据插入多个表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27671189/

10-12 17:47
查看更多