我正在尝试将2个实体保存到两个不同的表中,这些表与一对一相关。但是对我来说有一些奇怪的东西。请看下面的代码
public int CreateNotification(BusinessModel.Notification notification)
{
var db = new DataAccess.ApplicationDbContext();
var dbNotification = new DataAccess.Notification()
{
Name = notification.Name,
};
db.Notifications.Add(dbNotification);
//set NotificationSchedule
var dbNotificationSchedule = new DataAccess.NotificationSchedule()
{
Schedule = JsonConvert.SerializeObject(notification.NotificationSchedule)
};
db.NotificatoinSchedule.Add(dbNotificationSchedule);
***db.SaveChanges();***
此代码有效且通知的外键设置为通知计划权限。 但问题是如何 通知的ID设置为notificatioschedule的ID?如果我在savechange之后添加相关实体则会出现错误,"更新实体错误...."
var db = new DataAccess.ApplicationDbContext();
var dbNotification = new DataAccess.Notification()
{
Name = notification.Name,
};
db.Notifications.Add(dbNotification);
***db.SaveChanges();***
//set NotificationSchedule
var dbNotificationSchedule = new DataAccess.NotificationSchedule()
{
Schedule = JsonConvert.SerializeObject(notification.NotificationSchedule)
};
db.NotificatoinSchedule.Add(dbNotificationSchedule);
}
public class Notification
{
public int Id { get; set; }
public string Name { get; set; }
public virtual NotificationSchedule NotificationSchedules { get; set; }
}
public class NotificationSchedule
{
[ForeignKey("Notification")]
public int Id { get; set; }
public string Schedule { get; set; }
public virtual Notification Notification { get; set; }
}