【发布时间】:2014-12-28 10:07:09
【问题描述】:
我有这样的 JSON 数据:
{
"id":"",
"firstName":"John",
"lastName":"Doe",
"phones":[
{
"value":"555-555-555",
"$$hashKey":"object:8"
},
{
"value":"444-444-444",
"$$hashKey":"object:10"
}
],
"emails":[
{
"value":"example@mail.com",
"$$hashKey":"object:12"
},
{
"value":"othermail@mail.com",
"$$hashKey":"object:18"
}
],
"tags":[
{
"value":"friend",
"$$hashKey":"object:14"
},
{
"value":"john",
"$$hashKey":"object:16"
}
],
"address":"Route 44",
"city":"NY",
"bookmarked":"",
"notes":"It's John"
}
我想使用 ASP.NET MVC 实体框架(使用 Microsoft SQL 数据库)将此 JSON 数据存储到数据库中。我的模型是使用 ADO.NET 实体框架数据模型从数据库自动生成的。我面临的问题是,由于某种原因,它不会将电子邮件/电话和标签存储在数据库中。我尝试了所有我能找到的东西,但没有一个对我有用。有人知道问题出在哪里以及如何将此 JSON 存储到我的数据库中?
编辑 1:
在控制器中调试 contact 变量后,我注意到电子邮件、标签和电话模型数据为空。我不知道它们是如何以及为什么是空的......
我还将 CONSTRAINT 添加到所有外键
这是数据库模型:
这是从数据库自动生成的模型(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; }
}
这是向数据库添加数据的函数:
public string AddContact(Contact contact)
{
if (contact != null)
{
db.Contacts.Add(contact);
db.SaveChanges();
return "Contact Added";
}
else
{
return "Invalid Record";
}
}
【问题讨论】:
-
你遇到的错误是什么?
-
@Ofiris 没有错误...来自 JSON 对象的电话、标签和电子邮件数据未存储到数据库...
-
如果您将那些
HashSet<T>集合更改为List<T>会怎样? -
@dbc 让我试试。我会发回结果
-
@dbc 我试过你提到的问题它并没有解决我的问题
标签: c# asp.net asp.net-mvc json entity-framework