无法删除该对象,因为在ObjectStateManager#2中找不到该对象

时间:2013-03-17 22:35:55

标签: c# .net wpf database entity-framework

我在截图中遇到了问题: problem

以下是该计划开头的代码:

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

attach

EDIT,

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

nullable

1 个答案:

答案 0 :(得分:2)

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

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

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

WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();