实体框架和ICollection

时间:2014-07-03 06:49:54

标签: c# wpf entity-framework ef-code-first icollection

背景

我正在学习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; }
}

问题

  1. 我想在'Children'ICollection中修改一个Item来测试我对该过程的理解并检查它是否有效,但似乎没有简单的方法可以做到这一点;没有.Item(int x)方法(这个ICollection的目的是'仅用于参考',并且必须进行单独的查询?)
  2. 还是有其他方法可以做到吗?

    1. 还没有深入研究WPF DataBinding,是否可以将此ICollection绑定到表单上的控件并让用户操作我可以获取的数据并将更改保存到数据库?

2 个答案:

答案 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}" />                
相关问题