背景
我正在学习WPF(主要是为了好玩),正在构建一个小应用程序。
我创建了一个SQL Server数据库(仅限表),然后使用Entity Framework(EF)'Code First from Database'来生成数据库上下文和相关的模型类。
问题/误解
我有一个在另一个表中引用的表,因此EF生成一个类,其中包含子对象的ICollection(为了简单起见,表名等已修改):
[Table("Parent")]
public partial class Parent
{
//Other Properties etc
public virtual ICollection<Child> Children { get; set; }
}
问题
还是有其他方法可以做到吗?
答案 0 :(得分:0)
我更愿意控制导航属性而不是将其留给EF。将类修改为以下内容:
[Table("Parent")]
public partial class Parent
{
private List<Child> _children;
public Parent()
{
_children = new List<Child>();
}
// other properties, etc.
public List<Child> Children
{
get { return _children; }
set { _children = value; }
}
}
就DataBinding而言,您可以轻松地将任何ItemsControl的ItemsSource绑定到Child集合。例如:
<ComboBox ItemsSource="{Binding Path=Children}" />
上面的示例假设您的相对DataContext设置为您的Parent对象。
答案 1 :(得分:0)
据我所知,请看看这对你有帮助。
using (var db = new DataBaseEntity())
{
Child myChild = db.Parent.Select(x => x.Child);
myChild.IsSelected = true;
myChild.Name = "MyChildName";
db.SaveChanges() //EF Tracks the items so u could simple commit the changes to Db.
}
第二个问题:
我认为你不能直接将ICollection绑定到WPf ItemSource。尝试使用DTO或将它们序列化为Observable Collection,就像这样。
ObservableCollection<Child> childCollection = new ObservableCollection<Child>();
_childCollection .Add(new Child
{
// Serialize to Properties in the Child
});
// Bind the collection or property where u need
<List ItemSource="{Binding _ChildCollection}" />