Workaround for EF6.0 generated code without annotations

Source: Internet
Author: User
Tags deprecated documentation generator
Directory

Table of Contents first entity Framework60 find the problem to review the EF40 generated content ef40 Relational metadata I don't know, but I haven't looked at it carefully. Ef40 Container declaration to Ef40 entity collection Ef40 AddTo method ef40 entity Sound The Ef40 entity constructor ef40 The primitive property to see EF60 generated content Ef60 constructor ef60 entity set declaration EF60 entity declaration Problem Resolution The first step is to add a code generator for edmx that is ef6x dbcontext builder step two. Modify T4 template content modelcontexttt file Modeltt file summary

Preliminary entity Framework6.0

have been using VS2010 or VS2008, have been using the EF4.0 version ... Before, also used to model first of the EF design, because the feeling, in the design interface can better help ideas, at the same time, in the design interface is also easy to add some text description (these instructions will exist with the final generated entity classes).
   Find Problems

After installing the vs2013, I hastened to try the EF6.0 ... Tens of thousands of words omitted here.
Open a previously designed and completed project that contains the edmx file, and I want to see how the ef6.0 generated code differs from ef4.0.
Results found: ef6.0 (T4 template) generated CS file, unexpectedly did not include comments (edmx in the document), this let me why ah. first of all, to review the ef4.0 generated content ef4.0 relational metadata (do not know if you do not see, anyway, I have not read carefully)

#region EDM Relational Source metadata

[Assembly:edmrelationshipattribute ("Models", "Hospitalproject", "Hospital", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof (Hnwms. Efdata.hospital), "Project", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof (Hnwms. efdata.project))]
///
... [Assembly:edmrelationshipattribute ("Models", "Usermydisk", "User", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof (Hnwms. Efdata.user), "Mydisk", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof (Hnwms. Efdata.mydisk))]

#endregion
ef4.0 Container statement to

Container inherits from ObjectContext in ef4.0
The constructor (generated by default) has three.

    <summary>
    ///No metadata documents are available.
    ///</summary> Public
    partial class Container:objectcontext
ef4.0 Entity Collection

There are public properties with get accessors, as well as corresponding private fields. A completely object-oriented approach; The only downside is that there is no automatically generated annotation content (summary) for the entity collection.

        <summary>
        ///No metadata documents are available.
        ///</summary> public
        objectset<user> Users
        {
            get
            {
                if (_users = null))
                {
                    _users = base. Createobjectset<user> ("Users");
                }
                Return _users
            }
        }
        Private objectset<user> _users;
ef4.0 AddTo Method

Although it indicates "deprecated", it is convenient to call elsewhere, at least directly.

        <summary>
        ///The method used to add new objects to the Users EntitySet is deprecated. Please consider using the associated objectset&lt; instead T&gt; property of the. Add method.
        ///</summary> public
        void addtousers (user user)
        {
            base. AddObject ("Users", user);
        }
ef4.0 Entity Declaration

Added a lot of attribute statements, to be honest, I have never paid attention to these things, do not know what to do with.

    <summary>
    ///User base class (also describes headquarters staff)
    ///</summary>
    [Edmentitytypeattribute (namespacename= " Models ", name=" User ")]
    [Serializable ()] [
    DataContractAttribute (isreference=true)]
    [ KnownTypeAttribute (typeof (Projectmanager))]
    [KnownTypeAttribute (typeof (Hospitalservicer)]]
    [ KnownTypeAttribute (typeof (Nursingworker))] public
    partial class User:entityobject
ef4.0 Entity Constructors

Too big to look at, arguments are the permutations of all the attributes, and then add a global:: to exclude type conflicts; During development, I didn't seem to have used an entity constructor to construct an instance of an entity.

public static User CreateUser (global::system.string code, global::system.string Loginpassword, global::system.string Realname, global::system.string Mobilephoneno, global::system.string xType, global::system.string IDCordNO)
ef4.0 Primitive Properties

The

is in common with the entity collection, fully conforming to object-oriented writing, with attributes, and corresponding fields exist. In addition, the set accessor also displays four events that trigger a "self-tracking entity" (specifically what is a self tracking entity, which does not repeat here). )

///<summary>///user code///</summary>///<longdes cription>///Coding rules:& #xA; U opening + 4 digit sequential code & #xA; If 4-bit sequence code reaches 9999, it is & #xA;
        UA opening +3 is a digital sequential code & #xA; and so on & #xA; </LongDescription> [Edmscalarpropertyattribute (Entitykeyproperty=true, Isnullable=false)] [Datam  Emberattribute ()] public global::system.string Code {get {return
            _code; The set {if (_code!= value) {oncodechanging (v) 
                    Alue);
                    Reportpropertychanging ("Code");
                    _code = Structuralobject.setvalidvalue (value, false);
                    Reportpropertychanged ("Code");
                Oncodechanged (); }} private global::system.string _code; 

Although, I said in the above description mentioned a lot about ef4.0 "bad", but this does not mean that I do not agree with ef4.0. Here are a few things I understand about the benefits of EF: I still like EF because it's simple, easy to use, and it's easier to do a solution with MVC, WCF Data service, and I prefer vs-provided edmx designer, where I can do without other "idea-assisted" software, Can complete the "Data design" and "data relationship" carding work. By edmx I can easily add "documents" to the "Entity" property "Navigation Properties" (summary in the final code, which is why I wrote this article). )

Because there is a edmx file in the solution, it's easy to see the data design when others take over the solution, and it's easy to understand the data relationship.

So, I still use model or db one when everyone is yelling at EF code one. The so-called "the beholder, radish and Chinese cabbage," Daniel don't spray me. thank ^_&. and look at the EF6.0 generated content ef6.0 Constructors

Unlike EF4.0, there is not a lot of "metadata" content above the generated container. When I open this class, the first thing I feel is, ah. So easy.
Container inherited from DbContext, as for and ObjectContext what is different, please find a Niang or MSDN.

    public partial class Container:dbcontext
ef6.0 entity Set declaration

The first difference with ef4.0 is that the entity set is no longer a objectset type, but a dbset type; second, it simplifies get and set accessors (with fewer declarations of corresponding fields, and then conforms to the declarative method of implicit property accessors).
No, it's not there. Note there, ef4.0 at least one. "No metadata documents are available. "Note.

Public virtual Dbset<user> the Users {get; set;}
ef6.0 Entity Declaration

Unlike ef4.0, an entity's constructor is no longer bloated, has no arguments, and is simply given an initial value for the navigation property, and the get and set of the property is simplified, at first glance, as if the demo was written by a class like this.
However, in general with the entity set declaration, the annotation goes there, in the ef4.0, but the "document and the long description" in the EDMX is generated in the summary.

    Public partial class user
    {public
        user ()
        {this
            . Signins = new hashset<signin> ();
            This. Mymenus = new hashset<mymenu> ();
            This. Mydisks = new hashset<mydisk> ();
        }
        public string Code {get; set;}
        public string Loginpassword {get; set;}
        public string Realname {get; set;}
        public string Mobilephoneno {get; set;}
        public string XType {get; set;}
        public string Idcordno {get; set;}
        Public virtual icollection<signin> Signins {get; set;}
        Public virtual icollection<mymenu> Mymenus {get; set;}
        Public virtual icollection<mydisk> Mydisks {get; set;}
    }

It is a very simple and superficial description of the differences between ef4.0 and ef6.0, and describes my personal likes and dislikes. the need to solve the problem

See here, a lot of Daniel may say "brother, out man, everyone is now in 2015, you also 2013." "" is not a note. That must be either. ”
Brother I explain, oh, for several years, no work in the front-line, no code work, so for VS and other editors, etc., are not very familiar with ... Note but it's important. In particular,///summary annotations that meet vs requirements, because vs has smart tips Ah, I think we've all seen and used, when. When, there will be a lot of this type of property ah, method Ah ... come on. All are English, how to distinguish. Even if you are good e, excuse me, you are a person to develop the application system.
Oh, a little bit of logic.
Anyway, I'm going to yell "I want to comment." Whether it's a comment on the code I wrote, or a comment on the generated code, I want it. Also have to read to understand the annotation. ”
Quietly tell some birds that are more than me, in fact, the code (compliant) comments in VS are quite useful, such as when the development is complete, you can generate a CHM type or help view2.x type with annotations (not much here). solve the problem The first step is to add "code generators" to edmx that is, "ef6.x dbcontext generator."

Steps: Open edmx in vs. right-click the "Add code Build Item" and then select "Ef6.x dbcontext Builder" in the window that appears, and verify that validation: In Solution Explorer, the edmx file appears below the one you just added. Code generation Content ", commonly called Model.Context.tt and model.tt (in fact, these two things, is the T4 template, open it, and then press" Ctrl+s ", it will automatically execute, and according to the edmx file design, generate the relevant container, Dbset, entity) The second step modifies the T4 template content Model.Context.tt file

Find content:

    public string Dbset (EntitySet entityset,system.collections.generic.ienumerable< System.data.entity.core.metadata.edm.globalitem> itemcollection)
    {return
        string. Format (
            cultureinfo.invariantculture,
            "{0} virtual dbset<{1}> {2} {get; set;}}",
            Accessibility.forreadonlyproperty (EntitySet),
            _typemapper.gettypename (entityset.elementtype),
            _code. Escape (EntitySet), summary);
    

What is this method for? is actually returning a piece of text like a code

Public virtual Dbset<user> the Users {get; set;}

Change to be:

    public string Dbset (EntitySet entityset,system.collections.generic.ienumerable< System.data.entity.core.metadata.edm.globalitem> itemcollection)
    {
    String summary = EntitySet.ElementType.Documentation = null? "(Error Message:not have summary in edmx.)" : entitySet.ElementType.Documentation.Summary;
        return string.
            the set of Format (CultureInfo.InvariantCulture,
            "///<summary>\r\n\t///{3}" \r\n\t///</summary>\r\n\ t{0} virtual dbset<{1}> {2} {{get; set;}} ',
            accessibility.forreadonlyproperty (EntitySet),
            _ Typemapper.gettypename (Entityset.elementtype),
            _code. Escape (EntitySet), summary);
    

Oh, you may think, I wrote in the format, should not be beautiful ... My explanation is that this T4 will eventually not be compiled into the assembly, it doesn't matter.
In this way, the resulting content is similar to the following:

<summary>
///A collection of user base classes (which also describes the headquarters staff)
///</summary> public
virtual dbset<user> users {get; set;}
model.tt File

Find content:

foreach (var entity in typemapper.getitemstogenerate<entitytype> (itemcollection))
{
    Filemanager.startnewfile (entity. Name + ". cs");
    Beginnamespace (code);
#>

This code, that is, according to the type name of the entity, produce a separate CS file, and generate namespace declaration, if the type to add a comment, is not in the namespace below it ...
Change to be:

String summary=string. Empty;
foreach (var entity in typemapper.getitemstogenerate<entitytype> (itemcollection))
{
    Filemanager.startnewfile (entity. Name + ". cs");
    Beginnamespace (code);
    Summary = entity. Documentation = NULL? Entity. Name:entity. Documentation.summary;
#>
///<summary>
///<#=summary#>

It's not done yet, go on, find

    public string Property (Edmproperty edmproperty) {return string. Format (CultureInfo.InvariantCulture, "{0} {1}} {2} {{{} {{{3}get}]"; {4}set;
            } ", Accessibility.forproperty (Edmproperty), _typemapper.gettypename (Edmproperty.typeusage), _code. Escape (Edmproperty), _code. SpaceAfter (Accessibility.forgetter (Edmproperty)), _code.
    SpaceAfter (Accessibility.forsetter (Edmproperty))); public string NavigationProperty (NavigationProperty navprop) {var endtype = _typemapper.gettypename (NA
        VProp.ToEndMember.GetEntityType ()); return string. Format (CultureInfo.InvariantCulture, "{0} {1}} {2} {{{} {{{3}get}]"; {4}set; } ", Accessibilityandvirtual (Accessibility.fornavigationproperty (Navprop)), navProp.ToEndMember.Re Lationshipmultiplicity = = Relationshipmultiplicity.many? ("icollection<" + Endtype + ">"): Endtype, _code.
   Escape (Navprop),         _code. SpaceAfter (Accessibility.forgetter (Navprop)), _code.
    SpaceAfter (Accessibility.forsetter (Navprop))); }

Change to:

    public string Property (Edmproperty edmproperty) {return string. Format (CultureInfo.InvariantCulture, "///<summary>\r\n\t///{5}\r\n\t///</summary>\r\n\t{0} {1}") {2} {{{3}get; {4}set;
            } ", Accessibility.forproperty (Edmproperty), _typemapper.gettypename (Edmproperty.typeusage), _code. Escape (Edmproperty), _code. SpaceAfter (Accessibility.forgetter (Edmproperty)), _code. SpaceAfter (Accessibility.forsetter (Edmproperty)), edmproperty.documentation = = null?
    "": edmProperty.Documentation.Summary); public string NavigationProperty (NavigationProperty navprop) {var endtype = _typemapper.gettypename (NA
        VProp.ToEndMember.GetEntityType ()); return string. Format (CultureInfo.InvariantCulture, "///<summary>\r\n\t///{5}\r\n\t///</summary>\ R\n\t{0} {1} {2} {{{3}get; {4}set; }} ", AccessibilityandvirtuaL (Accessibility.fornavigationproperty (Navprop)), navProp.ToEndMember.RelationshipMultiplicity = = RELATIONSHIPM Ultiplicity. Many? ("icollection<" + Endtype + ">"): Endtype, _code. Escape (Navprop), _code. SpaceAfter (Accessibility.forgetter (Navprop)), _code. SpaceAfter (Accessibility.forsetter (Navprop)), navprop.documentation = = null?
    "": navProp.Documentation.Summary); }

Then "Save", the resulting CS file is similar to the bottom of the:

    <summary>
    ///User base class (also describes headquarters staff)
    ///</summary> public
    partial class user
    {
    ...
        ///<summary>
        ///user encoded
        ///</summary> public
        string code {get; set;}
    ......
    }

Ok. This will take care of the edmx generated content of the issue of no annotations.
Yelling again "notes are useful. " Summary

In short, I personally feel that in the use of a (others can be summed up with a series of) new things, must be considered from the designer's point of view, everything is useful.

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.