この記事では、LINQ to SQL のシリアル化機能について説明します。 以下の段落では、デザイン時のコード生成時にシリアル化を追加する方法と、LINQ to SQL クラスの実行時のシリアル化動作について説明します。
次のいずれかの方法で、デザイン時にシリアル化コードを追加できます。
オブジェクト リレーショナル デザイナーで、[ シリアル化モード ] プロパティを [一方向] に変更します。
SQLMetal コマンド ラインで、 /serialization オプションを追加します。 詳細については、「 SqlMetal.exe (コード生成ツール)」を参照してください。
概要
LINQ to SQL によって生成されるコードは、既定で遅延読み込み機能を提供します。 遅延読み込みは、必要に応じてデータを透過的に読み込むため、中間層で非常に便利です。 ただし、遅延読み込みが意図されているかどうかに関係なく、シリアライザーによって遅延読み込みがトリガーされるため、シリアル化には問題があります。 具体的には、オブジェクトがシリアル化されるときには、遅延読み込みされるすべての外部参照の推移的閉包がシリアル化されます。
LINQ to SQL のシリアル化機能は、主に次の 2 つのメカニズムを使用して、この問題に対処します。
遅延読み込みをオフにする DataContext モード (ObjectTrackingEnabled)。 詳細については、DataContextを参照してください。
生成されたエンティティに System.Runtime.Serialization.DataContractAttribute 属性と System.Runtime.Serialization.DataMemberAttribute 属性を生成するコード生成スイッチ。 この側面は、シリアル化での遅延読み込みクラスの動作を含め、このトピックの主なテーマです。
定義
DataContract シリアライザー: .NET Framework 3.0 以降のバージョンの Windows Communication Framework (WCF) コンポーネントによって使用される既定のシリアライザー。
一方向のシリアル化: 一方向の関連付けプロパティのみを含むクラスのシリアル化されたバージョン (サイクルを回避するため)。 規則により、主外部キーリレーションシップの親側のプロパティはシリアル化用にマークされます。 双方向関連付けのもう一方の側はシリアル化されません。
LINQ to SQL でサポートされているシリアル化の唯一の種類は、一方向シリアル化です。
コード例
次のコードでは、Northwind サンプル データベースの従来の Customer
クラスと Order
クラスを使用し、これらのクラスをシリアル化属性で修飾する方法を示します。
// The class is decorated with the DataContract attribute.
[Table(Name="dbo.Customers")]
[DataContract()]
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
{
' The class is decorated with the DataContract attribute.
<Table(Name:="dbo.Customers"), _
DataContract()> _
Partial Public Class Customer
Implements System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
// Private fields are not decorated with any attributes, and are
// elided.
private string _CustomerID;
// Public properties are decorated with the DataMember
// attribute and the Order property specifying the serial
// number. See the Order class later in this topic for
// exceptions.
public Customer()
{
this.Initialize();
}
[Column(Storage="_CustomerID", DbType="NChar(5) NOT NULL", CanBeNull=false, IsPrimaryKey=true)]
[DataMember(Order=1)]
public string CustomerID
{
get
{
return this._CustomerID;
}
set
{
if ((this._CustomerID != value))
{
this.OnCustomerIDChanging(value);
this.SendPropertyChanging();
this._CustomerID = value;
this.SendPropertyChanged("CustomerID");
this.OnCustomerIDChanged();
}
}
}
' Private fields are not decorated with any attributes,
' and are elided.
Private _CustomerID As String
' Public properties are decorated with the DataMember
' attribute and the Order property specifying the
' serial number. See the Order class later in this topic
' for exceptions
<Column(Storage:="_CustomerID", DbType:="NChar(5) NOT NULL", CanBeNull:=false, IsPrimaryKey:=true), _
DataMember(Order:=1)> _
Public Property CustomerID() As String
Get
Return Me._CustomerID
End Get
Set
If ((Me._CustomerID = value) _
= false) Then
Me.OnCustomerIDChanging(value)
Me.SendPropertyChanging
Me._CustomerID = value
Me.SendPropertyChanged("CustomerID")
Me.OnCustomerIDChanged
End If
End Set
End Property
// The following Association property is decorated with
// DataMember because it is the parent side of the
// relationship. The reverse property in the Order class
// does not have a DataMember attribute. This factor
// prevents a 'cycle.'
[Association(Name="FK_Orders_Customers", Storage="_Orders", OtherKey="CustomerID", DeleteRule="NO ACTION")]
[DataMember(Order=13)]
public EntitySet<Order> Orders
{
get
{
return this._Orders;
}
set
{
this._Orders.Assign(value);
}
}
' The following Association property is decorated with
' DataMember because it is the parent side of the
' relationship. The reverse property in the Order
' class does not have a DataMember attribute. This
' factor prevents a 'cycle.'
<Association(Name:="FK_Orders_Customers", Storage:="_Orders", OtherKey:="CustomerID", DeleteRule:="NO ACTION"), _
DataMember(Order:=13)> _
Public Property Orders() As EntitySet(Of [Order])
Get
Return Me._Orders
End Get
Set(ByVal value As EntitySet(Of [Order]))
Me._Orders.Assign(Value)
End Set
End Property
次の例の Order
クラスの場合、簡潔にするために、 Customer
クラスに対応する逆の関連付けプロパティのみが表示されます。 サイクルを回避するための DataMemberAttribute 属性はありません。
// The class for the Orders table is also decorated with the
// DataContract attribute.
[Table(Name="dbo.Orders")]
[DataContract()]
public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged
' The class for the Orders table is also decorated with the
' DataContract attribute.
<Table(Name:="dbo.Orders"), _
DataContract()> _
Partial Public Class [Order]
Implements System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
// Private fields for the Orders table are not decorated with
// any attributes, and are elided.
private int _OrderID;
// Public properties are decorated with the DataMember
// attribute.
// The reverse Association property on the side of the
// foreign key does not have the DataMember attribute.
[Association(Name = "FK_Orders_Customers", Storage = "_Customer", ThisKey = "CustomerID", IsForeignKey = true)]
public Customer Customer
' Private fields for the Orders table are not decorated with
' any attributes, and are elided.
Private _CustomerID As String
' Public properties are decorated with the DataMember
' attribute.
' The reverse Association property on the side of the
' foreign key does not have the DataMember attribute.
<Association(Name:="FK_Orders_Customers", Storage:="_Customer", ThisKey:="CustomerID", IsForeignKey:=true)> _
Public Property Customer() As Customer
エンティティをシリアル化する方法
前のセクションで示したコード内のエンティティは、次のようにシリアル化できます。
Northwnd db = new Northwnd(@"c\northwnd.mdf");
Customer cust = db.Customers.Where(c => c.CustomerID ==
"ALFKI").Single();
DataContractSerializer dcs =
new DataContractSerializer(typeof(Customer));
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
dcs.WriteObject(writer, cust);
writer.Close();
string xml = sb.ToString();
Dim db As New Northwnd("...")
Dim cust = (From c In db.Customers _
Where c.CustomerID = "ALFKI").Single
Dim dcs As New DataContractSerializer(GetType(Customer))
Dim sb As StringBuilder = New StringBuilder()
Dim writer As XmlWriter = XmlWriter.Create(sb)
dcs.WriteObject(writer, cust)
writer.Close()
Dim xml As String = sb.ToString()
自己再帰的リレーションシップ
自己再帰リレーションシップは、同じパターンに従います。 外部キーに対応する関連付けプロパティには DataMemberAttribute 属性がありませんが、親プロパティは属性を持っていません。
Employee.Manager/Reports と Employee.Mentor/Mentees という 2 つの自己再帰リレーションシップを持つ次のクラスについて考えてみましょう。
// No DataMember attribute.
public Employee Manager;
[DataMember(Order = 3)]
public EntitySet<Employee> Reports;
// No DataMember
public Employee Mentor;
[DataMember(Order = 5)]
public EntitySet<Employee> Mentees;
' No DataMember attribute
Public Manager As Employee
<DataMember(Order:=3)> _
Public Reports As EntitySet(Of Employee)
' No DataMember attribute
Public Mentor As Employee
<DataMember(Order:=5)> _
Public Mentees As EntitySet(Of Employee)