實體框架ChangeTracker未更新,返回“已刪除”實體

c# change-tracking entity-framework-core sqlite

我通過datagrid刪除行事件成功地從SQLite數據庫中刪除實體。這可以通過SQLite Manager確認。但是在運行此刪除事件和SaveChanges()命令後,我仍然在使用GetLocal()方法後獲取已刪除的實體。

這是deleteRow方法( Complete()調用SaveChanges() ):

private void dld_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete && !_isBeingEdited)
    {
        var grid = (DataGrid)sender;
        if (grid.SelectedItems.Count > 0)
        {
            var res = MessageBox.Show("Are you sure you want to delete " + grid.SelectedItems.Count + " devices?", "Deleting Records", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
            if (res == MessageBoxResult.Yes)
            {
                foreach (var row in grid.SelectedItems)
                {
                    Device device = row as Device;
                    _context.Devices.RemoveDevice(device);
                }
                _context.Complete();
                MessageBox.Show(grid.SelectedItems.Count + " Devices have being deleted!");
            }
            else
                DeviceListDataGrid.ItemsSource = _context.Devices.GetLocal();
        }
    }
}

下次加載實體時,我得到了正確的實體,但在運行GetLocal()後,我收到了之前刪除的實體?

加載:

    _context.Devices.Load();
    var devices = _context.Devices.GetLocal();
    DeviceListDataGrid.ItemsSource = devices;

GetLocal方法返回所有以前刪除的實體?

public ObservableCollection<TEntity> GetLocal()
{
    Context.GetService<DbContext>();
    var data = Context.ChangeTracker.Entries<TEntity>().Select(e => e.Entity);
    var collection = new ObservableCollection<TEntity>(data);

    collection.CollectionChanged += (s, e) =>
    {
        if (e.NewItems != null)
        {
            Context.AddRange(e.NewItems.Cast<TEntity>());
        }

        if (e.OldItems != null)
        {
            Context.RemoveRange(e.OldItems.Cast<TEntity>());
        }
    };

    return collection;
}

由於某種原因,行var data = Context.ChangeTracker.Entries<TEntity>().Select(e => e.Entity);在刪除之前仍然返回舊實體?

這是設備數據庫表:

CREATE TABLE "Device" (
    "DeviceId" INTEGER NOT NULL CONSTRAINT "PK_Device" PRIMARY KEY AUTOINCREMENT,
    "AdditionalInformation" TEXT,
    "Ampere" REAL,
    "Category" TEXT,
    "Category1CategoryId" INTEGER,
    "Description" TEXT,
    "DocumentIdentifier" TEXT,
    "GrossPrice" REAL,
    "HasErrors" INTEGER NOT NULL,
    "IsValid" INTEGER NOT NULL,
    "LeafletPath" TEXT,
    "Location" TEXT,
    "Name" TEXT,
    "NetPrice" REAL,
    "Notes" TEXT,
    "ProductCode" INTEGER NOT NULL,
    "ProductType" TEXT,
    "ProductType1ProductTypeId" INTEGER,
    "Supplier" TEXT,
    "Supplier1SupplierId" INTEGER,
    "TechData" TEXT,
    "TimeCreated" TEXT NOT NULL,
    "UseDefaultValuesFlag" INTEGER,
    "Watt" REAL,
    CONSTRAINT "FK_Device_Category_Category1CategoryId" FOREIGN KEY ("Category1CategoryId") REFERENCES "Category" ("CategoryId") ON DELETE RESTRICT,
    CONSTRAINT "FK_Device_ProductType_ProductType1ProductTypeId" FOREIGN KEY ("ProductType1ProductTypeId") REFERENCES "ProductType" ("ProductTypeId") ON DELETE RESTRICT,
    CONSTRAINT "FK_Device_Supplier_Supplier1SupplierId" FOREIGN KEY ("Supplier1SupplierId") REFERENCES "Supplier" ("SupplierId") ON DELETE RESTRICT
)

一般承認的答案

ChangeTracker當前保留表示已刪除實體的條目。對於更改跟踪器中的某些邊緣情況,這是故意完成的,儘管在將來的EF更新中可能會更改。

您可以通過篩選列表來避免選擇刪除實體的更改跟踪器條目。

Context
    .ChangeTracker
    .Entries<TEntity>()
    .Where(e => e.State != EntityState.Detached)
    .Select(e => e.Entity);


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因