我有一個遞歸數據結構,它有一個(空)父和一個(空)子集合。設置自引用類
我想將該數據結構保存到windows phone上的本地數據庫中。 我設置了一個DataContext,它工作的很好,但是當我想插入一個新的對象(它沒有父母和子女)時,我得到了「對象引用未設置爲對象的實例」。錯誤。
搜索後,我發現此線程LINQ to SQL: Self-referencing entity - ParentID/ChildID association,它聲明,由於父對象和子對象爲空,所以引發此異常。 但是,因爲這是一個允許的狀態,這不應該阻止我的代碼正常運行。
所以問題是:如何設置一個自引用類。
我迄今所做的:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Notepad.Codes.Models
{
[Table]
public class DirectoryItem
{
[Column(IsVersion=true)]
private Binary version;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int primaryKey;
private DirectoryItem parent;
[Association(Storage = "parent", ThisKey = "primaryKey", OtherKey = "primaryKey")]
public DirectoryItem Parent
{
get
{
return parent;
}
set
{
this.SetProperty(ref this.parent, value);
}
}
private EntitySet<DirectoryItem > children;
[Association(Storage = "children", OtherKey = "primaryKey")]
public EntitySet<DirectoryItem > Children
{
get
{
if(children == null)
children = new EntitySet<DirectoryItem >();
return children;
}
set
{
if (this.PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs("Children"));
this.children.Assign(value);
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Children"));
}
}
}
}
可能有人請告訴我,我怎麼也得使用或更改Associoaton
-Attribute,這樣我可以插入null的父母和孩子到我的數據庫?
沒有必要在標籤標題,有一個標籤系統。請閱讀http://meta.stackexchange.com/q/19190/147072瞭解更多信息。 – Patrick
你可以把你的例外的完整的調用堆棧嗎? –