1

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;
        }
    }
}

すべての DateTimes を明示的に datetime2 に設定しています。これらのモデルの Context クラスで Fluent API を使用して定義した N:N 関係は他にもいくつかありますが、これらの関係はすべて Schedule と他のモデルの間のものです。Shift には潜在的な関係が 1 つしかなく、それは親の Schedule との関係です。また、スケジュールには複数のシフトを含めることができるため、1:N / N:1 または 0 の関係は非常に簡単であると理解しています。

明らかにどこかで何かを見逃していますが、どこにあるのかわかりません。これのほとんどは数時間前まで機能していたことを知っており、他の関係を設定する際にいくつかの間違いを犯しましたが、それらをすべて削除し、すべての無関係な制約と値がテーブルから削除されました.

4

0 に答える 0