[英]Entity Framework and ICollection
Background 背景
I'm in the process of learning WPF (for fun mostly) and am building a little app to use. 我正在学习WPF(主要是为了娱乐),并正在构建一个小应用程序来使用。
I've created a SQL Server Database (Tables only), and then used Entity Framework (EF) 'Code First from Database' to generate the DB Context and associated Model classes. 我创建了一个SQL Server数据库(仅表),然后使用实体框架(EF)“数据库中的代码优先”生成数据库上下文和关联的模型类。
The Problem / Misunderstanding 问题/误解
I have a Table which is referenced in another Table, so EF generates a class with an ICollection of the child objects (table names etc modified for simplicity) : 我有一个在另一个表中引用的表,因此EF生成了一个带有子对象的ICollection的类(为简单起见 ,对表名等进行了修改) :
[Table("Parent")]
public partial class Parent
{
//Other Properties etc
public virtual ICollection<Child> Children { get; set; }
}
Questions 问题
or is there some other way to do it? 还是有其他方法可以做到?
I would prefer to be in control of the Navigation properties vs leaving it up to EF. 与将其留给EF相比,我更希望控制Navigation属性。 Modify the class to the following: 将该类修改为以下内容:
[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; }
}
}
As far as DataBinding is concerned, you can easily bind the ItemsSource of any ItemsControl to the Child collection. 就DataBinding而言,您可以轻松地将任何ItemsControl的ItemsSource绑定到Child集合。 For example: 例如:
<ComboBox ItemsSource="{Binding Path=Children}" />
The above example assumes your relative DataContext is set to your Parent object. 上面的示例假定您的相对DataContext设置为Parent对象。
As far i understand , Pls Look if this helps you. 据我了解,请看看这是否对您有帮助。
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.
}
Second question: 第二个问题:
I don't think You could directly bind ICollection into WPf ItemSource. 我认为您不能直接将ICollection绑定到WPf ItemSource。 Try a DTO or Serialize them into Observable Collection Like this. 尝试像这样的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}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.