1

我在屏幕截图中遇到了问题: 问题

这是程序开头的代码:

    public MainWindow()
    {
        InitializeComponent();


        BlackoutDates();

        variables.date = Convert.ToDateTime(MainCalendar.DisplayDate);
        DateOutput.Content = MainCalendar.DisplayDate.DayOfWeek + ", " + MainCalendar.DisplayDate.ToShortDateString();



    }

    //initialises entities
    WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
    private Booking ObjectIndex;

这是加载窗口时的代码

 private void Bookings_Loaded(object sender, RoutedEventArgs e)
    {


       WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
        // Load data into Rooms.
        var roomsViewSource = ((CollectionViewSource)(this.FindResource("roomsViewSource")));
        var roomsQuery = this.GetRoomsQuery(allensCroftEntities1);
        roomsViewSource.Source = roomsQuery.Execute(MergeOption.AppendOnly);

    }

这是导致错误的删除按钮的代码:

 private void btnDelete_Click(object sender, RoutedEventArgs e)
    {

        //prevents user trying to delete nothing/unselected row
        if (ObjectIndex == null)
        {
            MessageBox.Show("Cannot delete the blank entry");
        }
        else
        {

            //deletes object from dataset, saves it and outputs a message
            allensCroftEntities1.DeleteObject(ObjectIndex);

            allensCroftEntities1.SaveChanges();
            MessageBox.Show("Booking Deleted");
        }
    }

这是对象索引的代码:

   private void listrow_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        //outputs index of the selected room
        ObjectIndex = listrow.SelectedItem as Booking;
    }

编辑,

我试过

 allensCroftEntities1.Attach(ObjectIndex);

附

编辑,

当我注释掉预订加载事件中的实体时,我收到此错误,此代码过去可以正常工作,但我不知道为什么会发生所有这些问题。

可为空的

4

1 回答 1

2

首先尝试将实体附加到上下文:

allensCroftEntities1.Attach(ObjectIndex);
allensCroftEntities1.DeleteObject(ObjectIndex);

Bookings_Loaded或者通过删除该行来使用在类范围中声明的上下文而不是事件处理程序中的本地上下文:

WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
于 2013-03-17T22:37:46.987 回答