保存不公开外键属性/ datetime的实体时发生错误

时间:2013-10-25 21:53:18

标签: c# asp.net-mvc-4 entity-framework-4 ef-code-first

使用EF4遇到.NET MVC4中的Code-First模型的问题。我在Visual Studio 2012中,如果重要的话,连接到远程服务器。

每当我尝试使用代码中的一些默认值为数据库设定种子时,我都会收到以下错误:

---> System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while
saving entities that do not expose foreign key properties for their relationships. The
EntityEntries property will return null because a single entity cannot be identified as
the source of the exception. Handling of exceptions while saving can be made easier by
exposing foreign key properties in your entity types. See the InnerException for
details. 
---> System.Data.UpdateException: An error occurred while updating the entries. See the 
inner exception for details.
---> System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a 
datetime data type resulted in an out-of-range value.

我需要为我的模型使用GUID,但有问题的行是尝试调用以下内容:

// schedules is a list of schedules I've already created. 
foreach (var scheduleGuid in scheduleGuids)
{
    var s = scheduleGuids.IndexOf(scheduleGuid);
    var schedule = new Schedule
    {
        StartDate = new DateTime(1989, 1, 1),
        EndDate = new DateTime(1989, 1, 7),
        Id = scheduleGuid,
        Status = ScheduleStatus.Inactive,
        Recurring = true
    };


    var shifts = new List<Shift>();
    var shiftIndex = (s * 5);
    var days = shiftIndex + 5;
    for (var si = shiftIndex; si < (days); si++)
    {
        Debug.WriteLine("schedule {0}, shift {1}, total shift: {2}", s, (si > 5 ? si / 5 : si), si);
        var shiftGuid = shiftGuids[si];

        var d = shiftGuids.IndexOf(shiftGuid);
        var shift = new Shift {Schedule = schedule, Id = shiftGuid};
        switch (s)
        {
            case (0):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(6, 30);
                shift.Duration = (8.Hours() + 30.Minutes());
                break;
            case (1):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(6, 30);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
            case (2):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(8, 30);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
            case (3):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(9, 30);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
            case (4):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(11, 30);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
            case (5):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(22, 00);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
            case (6):
                shift.StartTime = schedule.StartDate.Add(d.Days()).At(20, 00);
                shift.Duration = (10.Hours() + 30.Minutes());
                break;
        }
        shift.Description = string.Format("{4}: {0} {1} {2}, {3} - Default Shift", shift.DayOfWeek, shift.StartTime.ToString("MMMM"), shift.DayOfMonth, shift.StartTime.ToString("yyyy"), Enum.GetName(typeof(ShiftType), shift.Type));
        //context.Shifts.AddOrUpdate(shift); 
        shifts.Add(shift);
    }

    schedule.Shifts = shifts;
    schedules.Add(schedule);
    context.Shifts.AddOrUpdate(shifts.ToArray());
    context.Schedules.AddOrUpdate(schedule);
}

context.Shifts.AddOrUpdate(shifts.ToArray());

失败了

以下是有问题的模型:

public class Schedule
{
    [Key]
    public Guid Id { get; set; }

    [ForeignKey("User")]
    public Guid? UserId { get; set; }

    public virtual ScheduleUser User { get; set; }

    public virtual ICollection<ScheduleRule> Rules { get; set; }

    public virtual ICollection<Shift> Shifts { get; set; }

    [Required]
    [DisplayFormat(NullDisplayText = "", DataFormatString= "{0:d}")]
    [Display(Name = "Start Date")]
    public DateTime StartDate { get; set; }

    [Required]
    [DisplayFormat(NullDisplayText = "", DataFormatString = "{0:d}")]
    [Display(Name = "End Date")]
    public DateTime EndDate { get; set; }

    [Required]
    public bool Recurring { get; set; }

    [Required]
    public bool Enabled { get; set; }

    public bool Temporary
    {
        get
        {
            return (ToBeEnabledOn.HasValue && ToBeDisabledOn.HasValue);
        }
    }

    [Column(TypeName = "datetime2")]
    public DateTime? EnabledOn { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? ToBeEnabledOn { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? DisabledOn { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? ToBeDisabledOn { get; set; }

    public ScheduleStatus Status { get; set; } // this is an enum
}

public class Shift
{
    [Key]
    public Guid Id { get; set; }

    public string Description { get; set; }

    public Schedule Schedule { get; set; }

    [ForeignKey("Schedule")]
    public Guid? ScheduleId { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? Start { get; set; }

    [NotMapped]
    public DateTime StartTime
    {
        get
        {
            return (Start ?? DateTime.Now);
        }
        set
        {
            Start = value;
        }
    }

    public long? TimeSpanDurationInTicks { get; set; }

    [NotMapped]
    public TimeSpan Duration
    {
        get
        {
            return new TimeSpan((TimeSpanDurationInTicks ?? 0));
        }
        set
        {
            TimeSpanDurationInTicks = value.Ticks;
        }
    }
}

我明确地将所有日期时间设置为datetime2。 我在Context类中使用Fluent API为这些模型定义了一些其他N:N关系,但所有这些关系都在Schedule和其他模型之间。 Shift只有一个潜在的关系,那就是它的父计划。并且时间表可以有几个班次,所以我的理解是这是一个非常简单的1:N / N:1或0关系。

我显然错过了某个地方,但我无法弄清楚在哪里。我知道大部分问题直到几个小时前才开始起作用,我在设置其他一些关系时犯了一些错误,但我已经删除了所有这些关系,所有无关的限制和值都从表中消失了。

0 个答案:

没有答案