我正在尝试使用Entity Framework为纯MVVM架构提供数据模型。它与'对象引用未设置为对象的实例'崩溃。设置一个简单的关系后,错误,该关系驱动视图模型从更改到数据模型。
模型非常简单:只是一个'产品'表。视图模型是一个简单的层次结构,其“Root”集合包含 ProductCollection 项的列表,这些项是数据模型中“Product”项的模型。作为MVVM应用程序,对数据模型的任何更改都通过事件处理程序驱动到视图模型中。实体框架事件处理程序似乎无法进行适度的事件级联。连接事件处理程序似乎会使EF崩溃。
第一个事件处理程序安装在此处:
/// <summary>
/// Initializes a new instance of the <see cref="RootCollection"/> class.
/// </summary>
/// <param name="compositionContainer">The composition container.</param>
public RootCollection(LicenseEntities licenseEntities)
{
// Initialize the object.
this.nameField = "Root";
this.licenseEntities = licenseEntities;
// Populate the root with the products.
foreach (Product product in this.licenseEntities.Products.ToList<Product>())
{
ProductCollection productCollection = new ProductCollection(
this.licenseEntities);
productCollection.ProductId = product.ProductId;
productCollection.Name = product.Name;
this.Add(productCollection);
}
// This will keep the view model reconcilled to the data model when the
// products change.
this.licenseEntities.Products.Local.CollectionChanged +=
this.OnProductChanged;
}
在实例化每个产品视图模型时安装第二个:
/// <summary>
/// Initializes a new instance of the <see cref="ProductCollection"/> class.
/// </summary>
/// <param name="licenseEntities">The DBContext for the license entities.</param>
public ProductCollection(LicenseEntities licenseEntities)
{
// Initialize the object.
this.licenseEntities = licenseEntities;
// Hook this object into the local collection change events. This line
// apparently kills Entity Framework. Comment it out to allow the products
// to be added to the model without throwing the exception.
this.licenseEntities.Products.Local.CollectionChanged +=
this.OnProductsChanged;
}
实例化产品时发生异常:
licenseEntities.Products.Add(
new Product
{
Name = "Explorer Chrome Suite",
ProductId = MainWindowViewModel.explorerChromeSuite
});
如果删除上面代码中的第二个事件处理程序,它可以正常工作,但在基础数据模型更改时不会更新视图模型中产品的名称。这是MVVM的基本功能,我很难相信实体框架是脆弱的和/或不适合MVVM模式的。可以从以下网址下载完整问题的完整解决方案: