序列化 (LINQ to SQL)

更新:November 2007

本主题介绍 LINQ to SQL 的序列化功能。下面几段提供了有关在设计时如何在代码生成期间添加序列化以及 LINQ to SQL 类的运行时序列化行为的信息。

您可以通过以下任一方法在设计时添加序列化代码:

概述

由 LINQ to SQL 生成的代码默认情况下提供延迟加载功能。延迟加载对在中间层以透明方式根据需要加载数据而言非常方便。但是,它会给序列化过程带来问题,原因是不论是否需要进行延迟加载,序列化程序都会触发延迟加载。实际上,对对象进行序列化时,会对其在所有出站延迟加载引用下的可传递闭包进行序列化。

LINQ to SQL 的序列化功能主要通过以下两种机制来解决此问题:

定义

  • 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()>  _
Partial Public Class Customer
    Implements System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
// The class is decorated with the DataContract attribute.
[Table(Name="dbo.Customers")]
[DataContract()]
public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged
{
    ' 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
    // 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();
            }
        }
    }
   ' 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
    // 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);
        }
    }

对于下例中的 Order 类,为简洁起见,只显示与 Customer 类对应的反向关联属性。它没有用来避免出现循环的 DataMember 属性。

' 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
// The class for the Orders table is also decorated with the
// DataContract attribute.
[Table(Name="dbo.Orders")]
[DataContract()]
public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged
    ' 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
    // 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

如何序列化实体

您可以按如下方式序列化上一节中显示的代码中的实体:

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()
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();

自递归关系

自递归关系遵循相同的模式。与外键对应的关联属性 (Property) 不具有 DataMember 属性 (Attribute),而父属性 (Property) 则具有。

请考虑以下具有两个自递归关系的类:Employee.Manager/Reports 和 Employee.Mentor/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)
// 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;

请参见

任务

如何:使实体可序列化 (LINQ to SQL)

参考

代码生成工具 (SqlMetal.exe)

其他资源

背景信息 (LINQ to SQL)