静的 Create メソッドを使用してオブジェクトを作成する方法 (Entity Framework)

エンティティ フレームワーク ツールは、概念スキーマ定義言語 (CSDL) ファイルを使用して、オブジェクト レイヤを定義するコードを生成します。データ クラスの生成時、それぞれのクラスは、静的な create ファクトリ メソッドを使用して生成されます。このメソッドは、オブジェクトをインスタンス化し、クラスの NULL に設定できないすべてのプロパティを設定するために使用します。このメソッドには、CSDL ファイル内で Nullable="false" 属性が適用されているすべてのプロパティに対するパラメータがあります。このメソッドは、多くの必須プロパティを持つオブジェクトを作成する場合に使用します。

このトピックの例には、Adventure Works Sales Model が使用されています。この例のコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、Entity Framework を使用するようにプロジェクトを構成しておく必要があります。具体的な方法については、「Entity Framework プロジェクトを手動で構成する方法」および「Entity Data Model を手動で定義する方法 (Entity Framework)」の手順を参照してください。

AdventureWorks Sales Model (EDM)SalesOrderHeader 型の CSDL の例を次に示します。

<EntityType Name="SalesOrderHeader">
  <Key>
    <PropertyRef Name="SalesOrderID" />
  </Key>
  <Property Name="SalesOrderID" Type="Int32" Nullable="false" />
  <Property Name="RevisionNumber" Type="Byte" Nullable="false" />
  <Property Name="OrderDate" Type="DateTime" Nullable="false" />
  <Property Name="DueDate" Type="DateTime" Nullable="false" />
  <Property Name="ShipDate" Type="DateTime" />
  <Property Name="Status" Type="Byte" Nullable="false" ConcurrencyMode="Fixed" />
  <Property Name="OnlineOrderFlag" Type="Boolean" Nullable="false" />
  <Property Name="SalesOrderNumber" Type="String" Nullable="false" MaxLength="25" Unicode="true" FixedLength="false" />
  <Property Name="PurchaseOrderNumber" Type="String" MaxLength="25" Unicode="true" FixedLength="false" />
  <Property Name="AccountNumber" Type="String" MaxLength="15" Unicode="true" FixedLength="false" />
  <Property Name="CustomerID" Type="Int32" Nullable="false" />
  <Property Name="SalesPersonID" Type="Int32" />
  <Property Name="TerritoryID" Type="Int32" />
  <Property Name="ShipMethodID" Type="Int32" Nullable="false" />
  <Property Name="CreditCardID" Type="Int32" />
  <Property Name="CreditCardApprovalCode" Type="String" MaxLength="15" Unicode="false" FixedLength="false" />
  <Property Name="CurrencyRateID" Type="Int32" />
  <Property Name="SubTotal" Type="Decimal" Nullable="false" Precision="19" Scale="4" />
  <Property Name="TaxAmt" Type="Decimal" Nullable="false" Precision="19" Scale="4" />
  <Property Name="Freight" Type="Decimal" Nullable="false" Precision="19" Scale="4" />
  <Property Name="TotalDue" Type="Decimal" Nullable="false" Precision="19" Scale="4" />
  <Property Name="Comment" Type="String" MaxLength="128" Unicode="true" FixedLength="false" />
  <Property Name="rowguid" Type="Guid" Nullable="false" />
  <Property Name="ModifiedDate" Type="DateTime" Nullable="false" />
  <NavigationProperty Name="Address" Relationship="AdventureWorksModel.FK_SalesOrderHeader_Address_BillToAddressID" FromRole="SalesOrderHeader" ToRole="Address" />
  <NavigationProperty Name="Address1" Relationship="AdventureWorksModel.FK_SalesOrderHeader_Address_ShipToAddressID" FromRole="SalesOrderHeader" ToRole="Address" />
  <NavigationProperty Name="Contact" Relationship="AdventureWorksModel.FK_SalesOrderHeader_Contact_ContactID" FromRole="SalesOrderHeader" ToRole="Contact" />
  <NavigationProperty Name="SalesOrderDetail" Relationship="AdventureWorksModel.FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID" FromRole="SalesOrderHeader" ToRole="SalesOrderDetail" />
</EntityType>

AdventureWorks の SalesOrderHeader クラスに対して生成された静的な CreateSalesOrderHeader メソッドの例を次に示します。

Public Shared Function CreateSalesOrderHeader(ByVal salesOrderID As Integer, _
    ByVal revisionNumber As Byte, ByVal orderDate As Date, ByVal dueDate As Date, _
    ByVal status As Byte, ByVal onlineOrderFlag As Boolean, _
    ByVal salesOrderNumber As String, ByVal customerID As Integer, _
    ByVal shipMethodID As Integer, ByVal subTotal As Decimal, ByVal taxAmt As Decimal, _
    ByVal freight As Decimal, ByVal totalDue As Decimal, ByVal rowguid As Global.System.Guid, _
    ByVal modifiedDate As Date) As SalesOrderHeader

    Dim salesOrderHeader As SalesOrderHeader = New SalesOrderHeader
    salesOrderHeader.SalesOrderID = salesOrderID
    salesOrderHeader.RevisionNumber = revisionNumber
    salesOrderHeader.OrderDate = orderDate
    salesOrderHeader.DueDate = dueDate
    salesOrderHeader.Status = status
    salesOrderHeader.OnlineOrderFlag = onlineOrderFlag
    salesOrderHeader.SalesOrderNumber = salesOrderNumber
    salesOrderHeader.CustomerID = customerID
    salesOrderHeader.ShipMethodID = shipMethodID
    salesOrderHeader.SubTotal = subTotal
    salesOrderHeader.TaxAmt = taxAmt
    salesOrderHeader.Freight = freight
    salesOrderHeader.TotalDue = totalDue
    salesOrderHeader.rowguid = rowguid
    salesOrderHeader.ModifiedDate = modifiedDate
    Return salesOrderHeader
End Function
public static SalesOrderHeader CreateSalesOrderHeader(int salesOrderID, 
    byte revisionNumber, global::System.DateTime orderDate, 
    global::System.DateTime dueDate, byte status, bool onlineOrderFlag, 
    string salesOrderNumber, int customerID, int shipMethodID, decimal subTotal, 
    decimal taxAmt, decimal freight, decimal totalDue, global::System.Guid rowguid, 
    global::System.DateTime modifiedDate)
{
    SalesOrderHeader salesOrderHeader = new SalesOrderHeader();
    salesOrderHeader.SalesOrderID = salesOrderID;
    salesOrderHeader.RevisionNumber = revisionNumber;
    salesOrderHeader.OrderDate = orderDate;
    salesOrderHeader.DueDate = dueDate;
    salesOrderHeader.Status = status;
    salesOrderHeader.OnlineOrderFlag = onlineOrderFlag;
    salesOrderHeader.SalesOrderNumber = salesOrderNumber;
    salesOrderHeader.CustomerID = customerID;
    salesOrderHeader.ShipMethodID = shipMethodID;
    salesOrderHeader.SubTotal = subTotal;
    salesOrderHeader.TaxAmt = taxAmt;
    salesOrderHeader.Freight = freight;
    salesOrderHeader.TotalDue = totalDue;
    salesOrderHeader.rowguid = rowguid;
    salesOrderHeader.ModifiedDate = modifiedDate;
    return salesOrderHeader;
}

静的な CreateSalesOrderHeader メソッドを使用して SalesOrderHeader オブジェクトを作成および保存する例を次に示します。

Dim productId As Integer = 777  'Mountain-100 Black, 44
Dim quantity As Short = 1
Dim lastName As String = "Adams"
Dim firstName As String = "Frances"
Dim invoiceNumber As String = "PO123456"
Dim shipMethod As Integer = 5
Dim specialOffer As Integer = 1

Using advWorksContext As New AdventureWorksEntities()
    Try
        ' Get the Contact for the specific customer 
        ' and the related address. 
        Dim customer As Contact = advWorksContext.Contact _
        .Include("SalesOrderHeader.Address") _
        .Where("it.LastName = @lastname", _
            New ObjectParameter("lastname", lastName)) _
        .Where("it.FirstName = @firstname", _
            New ObjectParameter("firstname", firstName)) _
        .First()

        ' Get the customer's address to use to create
        ' a new order with the same address.
        Dim address As Address = customer.SalesOrderHeader _
        .First().Address()

        ' Get the Product with the requested ID.
        Dim product As Product = _
            advWorksContext.Product.Where("it.ProductID = @product_id", _
            New ObjectParameter("product_id", productId)).First()

        ' Create a new SalesOrderHeader using the static 
        ' CreateSalesOrderHeader method.
        Dim order As SalesOrderHeader = _
            SalesOrderHeader.CreateSalesOrderHeader( _
            1, Convert.ToByte(1), DateTime.Now, DateTime.Today.AddMonths(2), _
            Convert.ToByte(1), False, String.Empty, customer.ContactID, shipMethod, _
            0, 0, 0, 0, Guid.NewGuid(), DateTime.Now)

        ' Set addition order properties.
        order.Address = address
        order.Address1 = address
        order.PurchaseOrderNumber = invoiceNumber

        ' Create a new SalesOrderDetail using the static 
        ' CreateSalesOrderDetail method.
        Dim item As SalesOrderDetail = _
            SalesOrderDetail.CreateSalesOrderDetail( _
            1, 0, quantity, product.ProductID, specialOffer, product.StandardCost, _
            0, 0, Guid.NewGuid(), DateTime.Now)

        ' Add item to the items collection and 
        ' add order to the orders collection.
        order.SalesOrderDetail.Add(item)
        customer.SalesOrderHeader.Add(order)

        ' Call a custom method to recalculate totals.
        ' For more information, see "Customizing Objects."
        order.UpdateOrderTotal()

        ' Save changes pessimistically. This means that changes 
        ' must be accepted manually once the transaction succeeds.
        advWorksContext.SaveChanges()

        Console.WriteLine("Order created with order number: " _
            + order.SalesOrderNumber)
    Catch ex As Exception
        Console.WriteLine(ex.ToString())
    End Try
End Using
int productId = 777; //Mountain-100 Black, 44
short quantity = 1;
string lastName = @"Adams";
string firstName = @"Frances";
string invoiceNumber = "PO123456";
int shipMethod = 5;
int specialOffer = 1;
 
using (AdventureWorksEntities advWorksContext = 
    new AdventureWorksEntities())
{
    try
    {
        // Get the Contact for the specific customer 
        // and the related address. 
        Contact customer = advWorksContext.Contact
            .Include("SalesOrderHeader.Address")
            .Where("it.LastName = @lastname", 
                new ObjectParameter("lastname", lastName))
            .Where("it.FirstName = @firstname", 
                new ObjectParameter("firstname", firstName))
            .First();

        // Get the customer's address to use to create
        // a new order with the same address.
        Address address = customer.SalesOrderHeader
            .First().Address;

        // Get the Product with the requested ID.
        Product product = 
            advWorksContext.Product.Where("it.ProductID = @product_id",
            new ObjectParameter("product_id", productId)).First();

        // Create a new SalesOrderHeader using the static 
        // CreateSalesOrderHeader method.
        SalesOrderHeader order = SalesOrderHeader.CreateSalesOrderHeader(0,
            Convert.ToByte(1), DateTime.Now, DateTime.Today.AddMonths(2),
            Convert.ToByte(1), false, string.Empty, customer.ContactID, shipMethod, 
            0, 0, 0, 0, Guid.NewGuid(), DateTime.Now);

        // Set addition order properties.
        order.Address = address;
        order.Address1 = address;
        order.PurchaseOrderNumber = invoiceNumber;

        // Create a new SalesOrderDetail using the static 
        // CreateSalesOrderDetail method.
        SalesOrderDetail item = SalesOrderDetail.CreateSalesOrderDetail(
            1, 0, quantity, product.ProductID, specialOffer, product.StandardCost, 
            0, 0,Guid.NewGuid(), DateTime.Now);

        // Add item to the items collection and 
        // add order to the orders collection.
        order.SalesOrderDetail.Add(item);
        customer.SalesOrderHeader.Add(order);

        // Call a custom method to recalculate totals.
        // For more information, see "Customizing Objects."
        order.UpdateOrderTotal();

        // Save changes pessimistically. This means that changes 
        // must be accepted manually once the transaction succeeds.
        advWorksContext.SaveChanges();

        Console.WriteLine("Order created with order number: "
            + order.SalesOrderNumber);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

参照

概念

オブジェクトの追加、変更、および削除 (Entity Framework)
Object Services の概要 (Entity Framework)