LINQ object classes, viewstate, and cache (A serialization and deserialization problem)

Source: Internet
Author: User

According to the description of msdn, The LINQ object class only supportsDatacontractattributeAttribute serialization operations, that is, they do not support serialization operations in the XML and bin formats, which makes it inconvenient for us to use the attributes,

For example, if there is a "student" LINQ entity class, an error occurs when we perform the following operations on it:

Student = new student (ID = 001, name = "ants", grade = "First Grade ");

When viewstate ["v"] = student; or page. cache ["p"] = student, an error indicating that the student type cannot be serialized will occur.

How can we deal with such problems? I thought it would be nice to add [datacontract] to the student class, but the result still won't work.

Let's solve this problem. After thinking for a long time, it prompts that the class cannot be serialized, so we can do it from the underlying layer, that is, implement serialization of this class by ourselves.

First, let the class implement the system. runtime. serialization. iserializable interface;

Then add the [serializable] feature to the class;

FinalCodeAs follows:


Public   Partial   Class Student: system. runtime. serialization. iserializable
Public T_helpcategory (serializationinfo, streamingcontext context)
This . ID = ( Int ) Info. getvalue ( " ID " , Typeof ( Int ));
This . Name = Info. getvalue ( " Name " , Typeof (String )) As   String ;
This . Grade = Info. getvalue ( " Grade " , Typeof (String )) As   String ;
# Region Iserializable Member

Public   Void Getobjectdata (serializationinfo info, streamingcontext context)
Info. addvalue ( " ID " , This . ID );
Info. addvalue ( " Name " , This . Name );
Info. addvalue ( " Grade " , This . Grade );

# Endregion


After such processing, the previous sample code will not go wrong. Of course, the results are correct.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.