Traps when using the WCF + Entity Framework for serialization

Source: Internet
Author: User

Be careful when using the WCF + Entity Framework. Otherwise,EasyFall into various traps. This section describes two problems that are easily encountered during serializationService stopped.

1. The service is stopped by trying to serialize the entity proxy class.

Ii. Service stops due to an endless loop during serialization;

No matter which trap you fallClientThe following dialog box is displayed (click to view the large image ):

Er ~ This figure is true:

It generally means that the service is not online, the client configuration is incorrect, or the proxy class is faulty. If Google follows the first line in error details, manyArticleAbout adjusting the data cache size and operation timeout ...... If you follow the conventional debugging method-as shown in the figure below to locate the problem, the deeper the problem may be.

 

When searching for problems, you must firstIllusion, See the problemNature-- The WCF Service is stopped for some reason. Second, we need to analyze the problemSpecial, Combined with experience to find problems.

There is a typical reason for the service to stop, that isSerialization failed. In WCF, serialization does not need to be written.CodeImplementation, while providing convenience for us, it also laid the groundwork. The use of EF further complicate things. There are advantages and disadvantages in everything. EF is often used.SpecialIn this way, we can find problems in more directionality.

What features does EF have to interact with WCF? Yes,We often use the entity class of EF as datacontract.. The entity class of EF, whether generated or written through code first, is run, to support some "advanced" functions of EF, for example, lazyload, runtime will be from your entity classAutomatically inherit a corresponding proxy type (proxy types)And perform operations on proxy objects. For example, when the person class is running, there will be a corresponding class named person123456 (this name is certainly not called, so it should be identified ). When we write code, the person operation will be changed to the person123456 operation.

In the debugging window, we can see the hidden class (the Code class is Handbook, and the actual class is dynamicproxies. handbook_ae28... 84 ):

In this way, in WCF, datacontractserializer will not recognize the account --I only know Lao Tzu (handbook), I don't know my son (proxy class), and I can't serialize it.! So it throws an exceptionService Interruption. In this way, we can see that it is no problem to return general objects using WCF. Once an object class object is returned, we will encounter an error at the beginning of the article.

 

A simple solution: Let dbcontext use static classes. Add a setting in the corresponding dbcontext constructor:

 
1:Public Partial ClassMtbcontainer: dbcontext
 
2:{
3:PublicMtbcontainer ()
 
4::Base("Name = mtbcontainer")
 
5:{
 
6:This. Configuration. proxycreationenabled =False;// This is the line added.
 
7:}
 
8://...
 
9:PublicIdbset <placepicturetype> placepicturetypes {Get; set ;}
10://...
 
11:}

 

The second common problem is the serialization of endless loops. At first glance, the error is the same as the first one:Service unavailableNow! It is also a serialization problem.

However, there is one such problemSpecial: Some object class objects can return normally, and some cannot.

After observation and analysis, it is found that the class that cannot be returned is often the entity class with the navigation attribute. For further analysis, the navigation attribute is usuallyConstitute indirect reference to itselfFor example, in a one-to-multiple table, one end usually has a set of multi-terminal objects, and one end of the Multi-terminal also has a reference. For example, if a parent object and a child object exist, an icollection <child> in the parent object is used to store all the children, in child, another parent is used to specify the child's parent. This mutual reference relationship causes datacontractserializerSerializationIt encountered a problem.

It seems that not only does EF encounter such a problem, datacontractserializer serializesDirectly or indirectly references your own class ObjectWill be in an endless loop.

 

Talking ...... Does the Visual Studio icon look like an endless loop? ^ V ^

 

Back to the question. The class described above is used as an example:

 
1:// [Datacontract (isreference = true)]
 
2:[Datacontract]
3:Public ClassParent
 
4:{
 
5:PublicParent ()
 
6:{
 
7:Children =NewList <child> ();
 
8:}
 
9:[Datamember]
 
10:Public StringName {Get; set ;}
 
11:[Datamember]
12:PublicIlist <child> children {Get; set ;}
 
13:}
 
14: 
 
15:// [Datacontract (isreference = true)]
 
16:[Datacontract]
 
17:Public ClassChild
 
18:{
 
19:[Datamember]
 
20:Public StringName {Get; set ;}
21:[Datamember]
 
22:PublicParent parentref {Get; set ;}
 
23:}
In the main function of the console applicatin, we try to use datacontractserializer to serialize it:
 
1:// Create mock objects
 
2:Parent P =NewParent () {name ="Baba"};
 
3:Child C1 =NewChild () {name ="John", Parentref = p };
4:Child C2 =NewChild () {name ="Alice", Parentref = p };
 
5:P. Children. Add (C1 );
 
6:P. Children. Add (C2 );
 
7:
 
8:// Creat datacontractserializer
 
9:Datacontractserializer serializer =NewDatacontractserializer (Typeof(Parent ));
 
10:
 
11:// Serialize & output results.
12:StringResult =Null;
 
13:Using(Stream S =NewMemorystream ())
 
14:{
 
15:Serializer. writeobject (S, P );
 
16:S. Seek (0, seekorigin. Begin );
 
17: 
 
18:Using(Streamreader r =NewStreamreader (s ))
 
19:{
20:Result = R. readtoend ();
 
21:}
 
22:}
 
23:Console. writeline (result );

The running result is: crash.By default, Datacontractserializer is like thisExpand objects layer by layer:

 
1:<Parent>
2:<Children>
 
3:<Child>
 
4:<Parent><! -- This is child. Parent property... Enter into endless loop -->
 
5:<Children>

It will not take into account the reference relationship, but will blindly convert the object attributes into corresponding XML elements. Therefore, parent-> Child1-> parent-> Child1...No shortage.

 

Solution 1: In the code above, use the isreference parameter on datacontract and set it to true. ([Datacontract (Isreference = true)]).

Solution 2: CallDatacontractserializerAnotherConstructorTo replace the 9th rows in the code above:

 
1:Datacontractserializer serializer =NewDatacontractserializer (Typeof(Parent ),
 
2:"Parent",
 
3:String. Empty,
 
4:Null,
 
5:Int. Maxvalue,
 
6:False,
7:True,
 
8:Null,
 
9:Null);

Row 7th indicates the use of preserve object reference. After preserve object reference is used, serialization results similar to the following code are generated,Each element has its own ID.:

 
1:<Parent Z: ID= "I1" Xmlns= "Http://schemas.datacontract.org/2004/07/Sealize" Xmlns: I= "Http://www.w3.org/2001/XMLSchema-instance" Xmlns: Z= "Http://schemas.microsoft.com/2003/10/Serialization">
 
2:<Children>
3:<Child Z: ID= "I2">
 
4:<Name>John</Name>
 
5:<Parentref Z: ref= "I1"/>
 
6:</Child>
7:<Child Z: ID= "I3">
 
8:<Name>Alice</Name>
 
9:<Parentref Z: ref= "I1"/>
 
10:</Child>
11:</Children>
 
12:<Name>Baba</Name>
 
13:</Parent>
The inaccuracy of the exception information of WCF makes it difficult to judge the problem. However, check the problem Nature , Analyze the problem Special In addition, the accumulation of some experience can quickly identify and solve the problem. Fake images always expose flaws. For example, although the error message prompts timeout, if an error is returned immediately after the service is called, it is generally not a timeout problem. If the error message says that data may exceed the size allowed to be returned, try to return a single object instead of a collection ...... Of course, we are still working hard to provide Visual Studio that is easier to use.

 

Reference resources

Working with poco entities

Proxydatacontractresolver class

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: info-contact@alibabacloud.com 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.