【发布时间】:2014-12-30 19:12:21
【问题描述】:
我在将数据更新到数据库时遇到问题。当我想更新数据时,Entity Framework 会向可以包含多行的表(具有外键的表)添加新行。
数据库模型:
当我更新电话/联系人或标签实体时,实体框架会自动添加新行而不是更新它
这是我使用的代码:
public string UpdateContact(Contact contact)
{
if (contact != null)
{
int id = Convert.ToInt32(contact.id);
Contact Updatecontact = db.Contacts.Where(a => a.id == id).FirstOrDefault();
Updatecontact.firstname = contact.firstname;
Updatecontact.lastname = contact.lastname;
Updatecontact.address = contact.address;
Updatecontact.bookmarked = contact.bookmarked;
Updatecontact.city = contact.city;
Updatecontact.notes = contact.notes;
Updatecontact.Emails1 = contact.Emails1;
Updatecontact.Phones1 = contact.Phones1;
Updatecontact.Tags1 = contact.Tags1;
db.SaveChanges();
return "Contact Updated";
}
else
{
return "Invalid Record";
}
}
编辑:
这是 EF 型号代码:
联系方式:
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; }
}
【问题讨论】:
-
关系是一对多还是一对一?
-
一对多是关系@beauXjames
-
好吧,您并没有真正加载 Emails1/Phones1/Tags1 对象,而是将它们设置为作为参数传入的它们的新实例......因为你可以有很多,那么它只是假设你想用新的 id 创建新的
标签: c# asp.net entity-framework asp.net-mvc-4