[英]Entity Framework and ICollection
背景
我正在学习WPF(主要是为了娱乐),并正在构建一个小应用程序来使用。
我创建了一个SQL Server数据库(仅表),然后使用实体框架(EF)“数据库中的代码优先”生成数据库上下文和关联的模型类。
问题/误解
我有一个在另一个表中引用的表,因此EF生成了一个带有子对象的ICollection的类(为简单起见 ,对表名等进行了修改) :
[Table("Parent")]
public partial class Parent
{
//Other Properties etc
public virtual ICollection<Child> Children { get; set; }
}
问题
还是有其他方法可以做到?
与将其留给EF相比,我更希望控制Navigation属性。 将该类修改为以下内容:
[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对象。
据我了解,请看看这是否对您有帮助。
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}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.