簡體   English   中英

實體框架和ICollection

[英]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; }
}

問題

  1. 我想修改“兒童” ICollection中的一個項目,以測試我對該過程的理解並檢查它是否有效,但是似乎沒有簡便的方法可以做到這一點; 沒有.Item(int x)方法(此ICollection是否旨在“僅供參考”,是否必須進行單獨的查詢?)

還是有其他方法可以做到?

  1. 尚未深入研究WPF DataBinding,是否可以將此ICollection綁定到表單上的控件,並讓用戶操縱數據,然后我可以將其保存並保存到DB中?

與將其留給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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM