因此,对于使用 Entity Framework 设计器来制作用作 MVVM 项目中的模型的 EDMX,我已经深陷困境了。
我刚刚遇到一个问题,我很确定 ICollection<>
那是代码生成的(例如见下文)确实需要是 ObservableCollection<>
将该集合绑定(bind)到 DataGrid
以期获得成功。
我认为我在修改 EF 代码生成以生成 ObservableCollections
的可能性方面获得了一些成功。而不是 ICollections
.有人试过成功吗?
我想另一种选择是让包含所选客户对象的 VM 也包含本地 ObservableCollection<Order>
在选择 Customer 对象时创建的...我只是担心上下文保存和保持数据同步。
与子对象集合关联的典型代码生成对象:
public partial class Customer
{
public Customer()
{
this.Orders = new HashSet<Order>();
}
public int Id { get; set; }
public System.DateTime Date { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
最佳答案
这就是我所做的,也是我首先使用 EF 数据库的方法。
这就是你需要生成的:
public partial class Parent
{
public Parent()
{
this.Children= new ObservableCollection<Child>();
}
这样默认的构造函数将被替换。 而 ObservableCollection 是 ICollection,因此您不需要更改任何其他内容。
要使它在每次更新数据库模型时都出现,您必须使用以下部分更改 .tt 文件:
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;{1}" +
"{2}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.ObjectModel;"
+ Environment.NewLine + "using System.Collections.Generic;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}
还有这个:
foreach (var navigationProperty in collectionNavigationProperties)
{
this.<#=code.Escape(navigationProperty)#> = new ObservableCollection<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
}
关于c# - 如何将 Entity Framework ICollection 更改为 ObservableCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17073114/