访问C#CollectionViewSource中的字段

时间:2018-03-13 09:47:23

标签: c# .net wpf entity-framework

我使用EF6访问数据库并从名为DbSet<Asset> Assets的表中检索DbSet实体(Asset)。

表的行存储在CollectionViewSource(CollectionViewSource x:Key="assetViewSource")中,它为WPF Xaml GUI提供DataContext

GUI的字段代表表的列,它们绑定到assetViewSource中的字段,如下所示:

Text="{Binding Path=AssetCategory, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"

一切正常,用户可以通过GUI与数据库进行交互。

任何人都可以告诉我如何在从GUI更新之后但在更改保存到RMS_DB数据库之前从后面的代码中访问assetViewSource集合中的数据?

我希望能够在代码中做一些事情,如下所示:

codebehindField = assetViewSource.Asset.AssetCategory.

1 个答案:

答案 0 :(得分:0)

我在https://msdn.microsoft.com/en-us/library/jj592677(v=vs.113).aspx的MSDN文档“实体框架使用属性值”部分的“获取并设置单个属性的当前值或原始值”部分中找到了回答此问题所需的信息。 我将发布我编写的代码以解决我的问题,以防其他人发现它有用....

    // Update "DateRecordLastUpdated" in GUI because changes have been made to the Process' fields.
    // Get the entity's primary key from the GUI and use it to Find the corresponding entity in the CollectionView.
    int OrgUnitID = int.Parse(viewAsset_assetOrgUnitIDTextBox.Text);
    int AssetClassID = int.Parse(viewAsset_assetAssetClassIDTextBox.Text);
    int AssetID = int.Parse(viewAsset_assetIDTextBox.Text);
    var selectedEntity = rmsDb.Assets.Find(OrgUnitID, AssetClassID, AssetID);       // Primary key components must be in sequence.
    rmsDb.Entry(selectedEntity).Property(u => u.DateRecordLastUpdated).CurrentValue = DateTime.UtcNow;
    BindingOperations.GetBindingExpression(viewAsset_dateRecordLastUpdated, TextBox.TextProperty).UpdateTarget();           //Trigger GUI binding refresh
    rmsDb.SaveChanges(); 

非常感谢那些评论我之前的帖子。