EF study notes-2 EF supports the implementation of complex types

Friends who have used .NET know that in our entity model, in addition to some simple models, there are also some complex types, such as types composed of several simple types; and EF is not only implementing basic additions, deletions and modifications In addition to checking, the implementation of complex types is also supported.

So how to manually construct 复杂类型(ComplexType)and simple actions of complex types? Generally, for example: a user table User, which has two fields FirstName and LastName, then the corresponding User entity class will have two attributes FirstName and LastName. If we want to combine FirstName and LastName into a UserName property, and we want to implement this idea in EF, we need to use complex types.

At present, since EF cannot explicitly support complex types, we cannot design the complex type in the visual designer in VS, so we can only temporarily modify the entity type manually so that the properties of complex types can be supported. There are the following steps:

  1. Generate solid model

  2. Modify the CSDL file

  3. Modify MSL files

  4. Regenerate model entity classes

In the subsequent introduction, I will add the complex attribute TelePhone for the entity class corresponding to the User table, where the complex attribute TelePhone consists of Tel, NickName, and Emal.

1. Generate a solid model

We can use the visual designer that comes with VS to implement the entity model. Friends who have understood the basics of EF should know this design, and the specific steps are repeated here. I generated the entity model UserInfoEntity.edmx.

Second, modify the CSDL file

After generating the entity file, we can use Notepad++ to open the entity model, find the part about the CSDL definition in the entity model, then find the definition section of the entity type named Users, delete the original Tel, NickName, Emal attribute definitions, and add a new one called TelePhone property node. The code looks like this:

 <EntityType Name="Users">
  <Key>
    <PropertyRef Name="UsersID" />
  </Key>
  <Property Name="UserID" Type="String" Nullable="false" MaxLength="5"
            Unicode="true" FixedLength="true" />
  <Property Name="CompanyName" Type="String" Nullable="false" MaxLength="40"
            Unicode="true" FixedLength="false" />
  <Property Name="ContactName" Type="String" MaxLength="30" Unicode="true"
            FixedLength="false" />
  <Property Name="ContactTitle" Type="String" MaxLength="30" Unicode="true"
            FixedLength="false" />
  <Property Name="Address" Type="NorthwindModel.CommonAddress"
            Nullable="false"></Property>
  <Property Name="Phone" Type="String" MaxLength="24" Unicode="true"
            FixedLength="false" />
  <Property Name="Fax" Type="String" MaxLength="24" Unicode="true"
            FixedLength="false" />
  <NavigationProperty Name="Orders"
                      Relationship="NorthwindModel.FK_Orders_Customers" FromRole="Customers" ToRole="Orders" />
  <NavigationProperty Name="CustomerDemographics"
                      Relationship="NorthwindModel.CustomerCustomerDemo" FromRole="Customers"
                      ToRole="CustomerDemographics" />
</EntityType>

Next, you need to add a CommonTelePhonedefinition called complex type, the specific code is as follows

<ComplexType Name="CommonTelePhone">
  <Property Name="Address" Type="String" MaxLength="60" Unicode="true" FixedLength="false" />
  <Property Name="NickName" Type="String" MaxLength="30" Unicode="true" FixedLength="false" />
  <Property Name="Region" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
  <Property Name="Emal" Type="String" MaxLength="10" Unicode="true" FixedLength="false" />
  <Property Name="Tel" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
</ComplexType>

At this point, the modification part of the CSDL has been completed.

3. MSL file

Find the definition of the MSL section and modify the mapping definition in the Users section. The code looks like this (please note ComplexProperty 节):

 <EntitySetMapping Name="Users">
  <EntityTypeMapping TypeName="IsTypeOf(NorthwindModel.Customers)">
    <MappingFragment StoreEntitySet="Customers">
      <ScalarProperty Name="UserID" ColumnName="CustomerID" />
      <ScalarProperty Name="CompanyName" ColumnName="CompanyName" />
      <ScalarProperty Name="ContactName" ColumnName="ContactName" />
      <ScalarProperty Name="ContactTitle" ColumnName="ContactTitle" />
      <ComplexProperty Name="Address" TypeName="NorthwindModel.CommonAddress">
        <ScalarProperty Name="Address" ColumnName="Address" />
        <ScalarProperty Name="NickName" ColumnName="NickName" />
        <ScalarProperty Name="Region" ColumnName="Region" />
        <ScalarProperty Name="Emal" ColumnName="Emal" />
        <ScalarProperty Name="Tel" ColumnName="Tel" />
      </ComplexProperty>
      <ScalarProperty Name="Phone" ColumnName="Phone" />
      <ScalarProperty Name="Fax" ColumnName="Fax" />
    </MappingFragment>
  </EntityTypeMapping>
</EntitySetMapping>

At this point, the modification part of MSL has been completed.

Fourth, regenerate the entity class file

We can use the EmdGen2tool to regenerate the entity class .cs file. How to EmdGen2use the tool is not introduced here. For details, you can Baidu or check my EmdGen2blog about how to use the tool later. Then the specific operation here is as follows.

Copy the modified model file (edmx) to the emdgen2.exe directory, and then enter: Emdgen2 /codegen cs NorthwindEnites.edmx on the command line. After executing this command, a NorthwindEnites.cs file, which is the code file of the entity class, will be generated in the current folder. Then change the file name to: NorthwindEnites.Designer.cs, this step mainly corresponds to edmx.

Finally, add the NorthwindEnites.edmx and NorthwindEnites.Designer.cs files to the project.
At this point, the modification of the composite type is completed.

According to the above steps, we can also add a complex type attribute of Address to Employees.
Next, let's look at the specific usage code:

Inquire

public void TestAddress()
        {
            using (var db = new NorthwindModel.NorthwindEntities1())
            {
                Console.WriteLine("Get first users addresss :");
                var cts = db.Customers.Take(5);
                foreach (var c in cts)
                {
                    Console.WriteLine("Address:{0},Tel:{1},NickName:{2},Emal:{3}",
                        c.Address.Address, c.Address.Tel, c.Address.NickName, c.Address.Emal);
                }
                Console.WriteLine("Get first Employess address:");
                var emp = db.Customers.Take(5);
                foreach (var c in emp)
                {
                    Console.WriteLine("Address:{0},Tel:{1},NickName:{2},Emal:{3}",
                        c.Address.Address, c.Address.Tel, c.Address.NickName, c.Address.Emal);
                }
            }
        }

Add to

public void AddTest()
        {
            using (var db = new NorthwindModel.NorthwindEntities1())
            {
                var customer = new NorthwindModel.Customers
                {
                    UserID = "340956",
                    CompanyName = "JinShan Company",
                    ContactName = "xray2017",
                    Address = new NorthwindModel.CommonAddress
                    {
                        Address = "WuHan,China",
                        NickName = "AiXiaoJun",
                        Tel = "15290896766",
                        Emal = "[email protected]",
                        Region = "LiuHeng"
                    }
                };
                db.AddToCustomers(customer);
                db.SaveChanges();
                var cst = db.Customers.FirstOrDefault(c => c.CustomerID == "2009");
                Assert.IsNotNull(cst);
                Console.WriteLine("UserID:{0},CompanyName:{1},ContactName:{2},NickName:{3},Tel:{4}",
                    cst.UserID, cst.CompanyName, cst.ContactName, cst.Address.NickName, cst.Address.Tel);
            }
        }

If there is something wrong, please criticize and correct, and learn from each other!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325368488&siteId=291194637