【发布时间】:2015-02-24 14:17:52
【问题描述】:
目前我正在学习 ASP.NET,我坚持将数据存储到多个表中。数据库模型如下图:
我想要实现的是当我将新联系人添加到联系人表以获取最后插入 ID 并自动插入表电话/标签/电子邮件的数据(如果该表有一些数据)。是否有机会在单个查询中执行此操作,还是我需要为每个表运行新查询?
这是控制器中使用的模型:
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; }
}
这是向数据库添加新行的控制器类:
public string AddContact(Contact contact)
{
if (contact != null)
{
db.Contacts.Add(contact);
db.SaveChanges();
return "Contact Added";
}
else
{
return "Invalid Record";
}
}
【问题讨论】:
-
MySQL 不支持,你可以在这里看到:stackoverflow.com/questions/3860280/…
-
我正在使用 Microsoft SQL Server @OndrejTokar
-
@TDF 我没有使用 mySQL。
-
您使用的是 MVC 和 Code First Entity Framework 方法对吗?
标签: c# sql asp.net asp.net-mvc-4