我正在尝试将JSON对象保存到SQL Server数据库。 因此,我在数据库中创建了两个表,“约会”和“邀请者”。
我生成的Json数据以及我使用jQuery $ .ajax()发送的数据是
{"Title":"Test",
"Description":"fffffff",
"Duration":"15 minuten",
"Invitee":[
{
"Email":"e@g.com",
"Presence":"nodig"
},
{
"Email":"h@g.com",
"Presence":"gewenst"
},
{
"Email":"j@z.com",
"Presence":"info"
}
]
}
这两个表是
CREATE TABLE [dbo].[Appointments] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[Title] NVARCHAR (100) NOT NULL,
[Description] NTEXT NULL,
[Duration] NVARCHAR (20) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
和
CREATE TABLE [dbo].[Invitees] (
[Id] INT NOT NULL,
[AppId] INT NOT NULL,
[Email] NVARCHAR (100) NOT NULL,
[Presence] NVARCHAR (15) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
此外,我创建了这些模型,类和接口
public class Appointment : IAppointments
{
#region Implementation of IAppointments
public int Id { get; set; }
public int UserId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Duration { get; set; }
public List<Invitee> Invitee { get; set; }
#endregion
};
interface IAppointments
{
int Id { get; set; }
int UserId { get; set; }
string Title { get; set; }
string Description { get; set; }
string Duration { get; set; }
List<Invitee> Invitee { get; set; }
};
和
public class Invitee : IInvitee
{
public int Id { get; set; }
public int AppId { get; set; }
public string Email { get; set; }
public string Presence { get; set; }
};
interface IInvitee
{
int Id { get; set; }
int AppId { get; set; }
string Email { get; set; }
string Presence { get; set; }
};
在控制器中我有以下代码
[HttpPost]
public JsonResult NewAppSave(Appointment model)
{
if (ModelState.IsValid)
{
using (var db = new MainDbContext())
{
var appointment = db.Appointments.Create();
var invitee = db.Invitees.Create();
appointment.UserId = 1;
appointment.Title = model.Title;
appointment.Description = model.Description;
appointment.Duration = model.Duration;
db.Appointments.Add(appointment);
foreach (var inv in model.Invitee)
{
var newInv = new Invitee();
invitee.Email = newInv.Email;
invitee.Presence = newInv.Presence;
};
db.Invitees.Add(invitee);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("", "Something went wrong");
}
return Json(model);
};
在foreach循环中的'model.Invitee'处生成NullReferenceException。
我无法弄清问题是什么。请帮帮....