How to: Map Custom Objects to Entities (Entity Framework)

.NET Framework 3.5

When you use custom data classes with an Entity Data Model (EDM), you must apply EDM attributes that map the custom classes and properties to entities defined in the conceptual model. The names of the classes and properties must match the names of entity types and properties in the conceptual model. You must also update the custom data class to do one of the following:

For more information, see Object-Entity Mapping Attributes (Entity Framework).

To add EDM attributes to custom data classes

  1. Add the following using statements (Imports in Visual Basic) to the code page:

    using System.Data;
    using System.Data.Objects.DataClasses;
    using System.Data.Metadata.Edm;
    using Microsoft.Samples.Entity;
    
    
  2. Insert EdmSchemaAttribute just above the namespace declaration.

  3. Add one instance of EdmRelationshipAttribute for each association. This attribute specifies the name and namespace of the association, the names of the roles in the association, the types in the association, and the multiplicity at each end of the association, such as one-to-one or one-to-many. Do this just above the namespace declaration.

  4. Add EdmEntityTypeAttribute to each class that maps to an entity type.

  5. Add EdmScalarPropertyAttribute to the property of each class that represents the entity key, which is used to uniquely identify objects. Specify a value of true for the EntityKeyProperty property of this attribute.

  6. Add EdmScalarPropertyAttribute to the remaining properties. If the property does not accept null values, specify a value of false for the IsNullable property on this attribute.

Example

This example shows EDM attributes applied to Order and LineItem classes. These custom classes are mapped to the SalesOrderHeader and SalesOrderDetail tables in the AdventureWorks database. Both classes inherit from EntityObject.

using System;
using System.Data.SqlTypes;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Data.Metadata.Edm;
using Microsoft.Samples.Entity;

[assembly: EdmSchemaAttribute()]
[assembly: EdmRelationshipAttribute("Microsoft.Samples.Entity",
    "LineItem_Order_OrderId", "Order",
    RelationshipMultiplicity.One, typeof(Order), "LineItems",
    RelationshipMultiplicity.Many, typeof(LineItem))]
namespace Microsoft.Samples.Entity
{   
    [EdmEntityTypeAttribute(NamespaceName="Microsoft.Samples.Entity",Name="Order")]
    public class Order : EntityObject 
    {
        // Define private property variables.
        private int _orderId;
        private byte _revision;
        private DateTime _orderDate;
        private DateTime _dueDate;
        private DateTime _shipDate;
        private bool _onlineOrder;
        private byte _status;
        private int _customer;
        private int _contact;
        private int _billToAddress;
        private int _shipToAddress;
        private int _shipMethod;
        private decimal _subTotal;
        private decimal _tax;
        private decimal _freight;
        private decimal _totalDue;
        private Guid _rowGuid;
        private DateTime _modifiedDate;
        private OrderInfo _extendedInfo;

        // Public properties of the Order object.
        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
        public int OrderId
        {
            get 
            {
                return _orderId;
            }
            set
            {
                ReportPropertyChanging("OrderId");
                _orderId = value;
                ReportPropertyChanged("OrderId");
            }
        }

        // Navigation property that returns a collection of line items.
        [EdmRelationshipNavigationPropertyAttribute("Microsoft.Samples.Entity", "LineItem_Order_OrderId", "LineItems")]
        public EntityCollection<LineItem> LineItems
        {
            get
            {
                return ((IEntityWithRelationships)(this)).RelationshipManager.
                    GetRelatedCollection<LineItem>("Microsoft.Samples.Entity.LineItem_Order_OrderId", "LineItems");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public byte Revision
        {
            get
            {
                return _revision;
            }
            set
            {
                if (_revision != value)
                {
                    ReportPropertyChanging("Revision");
                    _revision = value;
                    ReportPropertyChanged("Revision");
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public DateTime OrderDate 
        {
           get 
            {
                return _orderDate;
            }
            set
            {
                ReportPropertyChanging("OrderDate");
                _orderDate = value;
                ReportPropertyChanged("OrderDate");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public DateTime DueDate 
        {
            get 
            {
                return _dueDate;
            }
            set
            {
                ReportPropertyChanging("DueDate");
                _dueDate = value;
                ReportPropertyChanged("DueDate");
            }
        }
        [EdmScalarPropertyAttribute()]
        public DateTime ShipDate
        {
            get
            {
                return _shipDate;
            }
            set
            {
                ReportPropertyChanging("ShipDate");
                _shipDate = value;
                ReportPropertyChanged("ShipDate");

            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public bool OnlineOrder
        {
            get
            {
                return _onlineOrder;
            }
            set
            {
                if (_onlineOrder != value)
                {
                   ReportPropertyChanging("OnlineOrder");
                   _onlineOrder = value;
                   ReportPropertyChanged("OnlineOrder");
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public byte Status
        {
            get 
            {
                return _status;
            }
            set
            {
                if (_status != value)
                {
                    ReportPropertyChanging("Status");
                    _status = value;
                    ReportPropertyChanged("Status");
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int Customer
        {
            get
            {
                return _customer;
            }
            set
            {
                ReportPropertyChanging("Customer");
                _customer = value;
                ReportPropertyChanged("Customer");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int Contact
        {
            get
            {
                return _contact;
            }
            set
            {
                ReportPropertyChanging("Contact");
                _contact = value;
                ReportPropertyChanged("Contact");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int BillToAddress
        {
            get
            {
                return _billToAddress;
            }
            set
            {
                ReportPropertyChanging("BillToAddress");
                _billToAddress = value;
                ReportPropertyChanged("BillToAddress");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int ShipToAddress
        {
            get
            {
                return _shipToAddress;
            }
            set
            {
                ReportPropertyChanging("ShipToAddress");
                _shipToAddress = value;
                ReportPropertyChanged("ShipToAddress");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int ShipMethod
        {
            get
            {
                return _shipMethod;
            }
            set
            {
                ReportPropertyChanging("ShipMethod");
                _shipMethod = value;
                ReportPropertyChanged("ShipMethod");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public decimal SubTotal
        {
            get
            {
                return _subTotal;
            }
            set 
            {
                if (_subTotal != value)
                {
                    // Validate the value before setting it.
                    if (value < 0)
                    {
                        throw new ApplicationException(string.Format(
                                  Errors.propertyNotValidNegative,
                                  new string[2] { value.ToString(), "SubTotal" }));
                    }

                    ReportPropertyChanging("SubTotal");
                    _subTotal = value;
                    ReportPropertyChanged("SubTotal");

                    // Recalculate the order total.
                    CalculateOrderTotal();
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public decimal Tax
        {
            get
            {
                return _tax;
            }
            set
            {
                // Validate the value before setting it.
                if (value < 0)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidNegative,
                              new string[2] { value.ToString(), "Tax" }));
                }

                ReportPropertyChanging("Tax");
                _tax = value;
                ReportPropertyChanged("Tax");

                // Recalculate the order total.
                CalculateOrderTotal();
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public decimal Freight
        {
            get
            {
                return _freight;
            }
            set
            {
                if (_freight != value)
                {
                    // Validate the value before setting it.
                    if (value < 0)
                    {
                        throw new ApplicationException(string.Format(
                                  Errors.propertyNotValidNegative,
                                  new string[2] { value.ToString(), "Freight" }));
                    }

                    ReportPropertyChanging("Freight");
                    _freight = value;
                    ReportPropertyChanging("Freight");

                    // Recalculate the order total.
                    CalculateOrderTotal();
                }
            }

        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public Guid RowGuid
        {
            get
            {
                return _rowGuid;
            }
            set
            {
                ReportPropertyChanging("RowGuid");
                _rowGuid = value;
                ReportPropertyChanged("RowGuid");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public DateTime ModifiedDate
        {
            get
            {
                return _modifiedDate;
            }
            set
            {
                ReportPropertyChanging("ModifiedDate");
                _modifiedDate = value;
                ReportPropertyChanged("ModifiedDate");
            }
        }
        public decimal TotalDue
        {
            get
            {
                return _totalDue;
            }
        }

        [EdmComplexPropertyAttribute()]
        public OrderInfo ExtendedInfo
        {
            get
            {
                return _extendedInfo;
            }
            set
            {
                this.ReportPropertyChanging("ExtendedInfo");
                _extendedInfo = value;
                this.ReportPropertyChanged("ExtendedInfo");                
            }
        }
        private void CalculateOrderTotal()
        {
            // Update the total due as a sum of the other cost properties.
            _totalDue = _subTotal + _tax + _freight;
        }
}
    [EdmComplexTypeAttribute(NamespaceName = 
        "Microsoft.Samples.Entity", Name = "OrderInfo")]
    public partial class OrderInfo : ComplexObject
    {
        private string _orderNumber;
        private string _purchaseOrder;
        private string _accountNumber;
        private string _comment;

        [EdmScalarPropertyAttribute(IsNullable = false)]
        public string OrderNumber
        {
            get
            {
                return _orderNumber;
            }
            set
            {
                // Validate the value before setting it.
                if (value.Length > 25)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidString,
                              new string[3] { value, "OrderNumber", "25" }));
                }

                ReportPropertyChanging("OrderNumber");
                _orderNumber = value;
                ReportPropertyChanged("OrderNumber");
            }
        }
        [EdmScalarPropertyAttribute()]
        public string PurchaseOrder
        {
            get
            {
                return _purchaseOrder;
            }
            set
            {
                // Validate the value before setting it.
                if ((value != null) && value.Length > 25)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidString,
                              new string[3] { value, "PurchaseOrder", "25" }));
                }
                if (_purchaseOrder != value)
                {
                    ReportPropertyChanging("PurchaseOrder");
                    _purchaseOrder = value;
                    ReportPropertyChanged("PurchaseOrder");
                }
            }
        }
        [EdmScalarPropertyAttribute()]
        public string AccountNumber
        {
            get
            {
                return _accountNumber;
            }
            set
            {
                // Validate the value before setting it.
                if ((value != null) && value.Length > 15)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidString,
                              new string[3] { value, "AccountNumber", "15" }));
                }
                ReportPropertyChanging("AccountNumber");
                _accountNumber = value;
                ReportPropertyChanged("AccountNumber");
            }
        }
        [EdmScalarPropertyAttribute()]
        public string Comment
        {
            get
            {
                return _comment;
            }
            set
            {
                // Validate the value before setting it.
                if ((value != null) && value.Length > 128)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidString,
                              new string[3] { value, "Comment", "128" }));
                }
                if (_comment != value)
                {
                    ReportPropertyChanging("Comment");
                    _comment = value;
                    ReportPropertyChanged("Comment");
                }
            }
        }
    }

    [EdmEntityTypeAttribute(NamespaceName = "Microsoft.Samples.Entity", Name = "LineItem")]
    public class LineItem : EntityObject  
    {
        // Define private property variables.
        private int _orderId;
        private int _lineItemId;
        private string _trackingNumber;
        private short _quantity;
        private int _special;
        private int _product;
        private decimal _price;
        private decimal _discount;
        private decimal _total;
        private Guid _rowGuid;
        private DateTime _modifiedDate;

        // Default constructor.
        public LineItem()
        {

        }

        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
        public int OrderId
        {
            get
            {
                return _orderId;
            }
            set
            {
                ReportPropertyChanging("OrderId");
                _orderId = value;
                ReportPropertyChanged("OrderId");
            }
        }
        // Defines a navigation property to the Order class.
        [EdmRelationshipNavigationPropertyAttribute("Microsoft.Samples.Entity", "LineItem_Order_OrderId", "Order")]
        public Order Order
        {
            get
            {
                return ((IEntityWithRelationships)(this)).RelationshipManager.
                    GetRelatedReference<Order>("LineItem_Order_OrderId", "Order").Value;
            }
            set
            {
                ((IEntityWithRelationships)(this)).RelationshipManager.
                    GetRelatedReference<Order>("LineItem_Order_OrderId", "Order").Value = value;
            }
        }
        [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
        public int LineItemId
        {
            get
            {
                return _lineItemId;
            }
            set
            {
                ReportPropertyChanging("LineItemId");
                _lineItemId = value;
                ReportPropertyChanged("LineItemId");
            }
        }
        [EdmScalarPropertyAttribute()]
        public string TrackingNumber
        {
            get
            {
                return _trackingNumber;
            }
            set
            {
                if (_trackingNumber != value)
                {
                    // Validate the value before setting it.
                    if (value.Length > 25)
                    {
                        throw new ApplicationException(string.Format(
                                  Errors.propertyNotValidString,
                                  new string[3] {value,"TrackingNumber", "25"}));
                    }
                    ReportPropertyChanging("TrackingNumber");
                    _trackingNumber = value;
                    ReportPropertyChanged("TrackingNumber");
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public short Quantity
        {
            get
            {
                return _quantity;
            }
            set
            {
                if (_quantity != value)
                {
                    // Validate the value before setting it.
                    if (value < 1)
                    {
                        throw new ApplicationException(string.Format(
                                  Errors.propertyNotValidNegative,
                                  new string[2] { value.ToString(), "Quantity" }));
                    }
                    ReportPropertyChanging("Quantity");
                    _quantity = value;
                    ReportPropertyChanged("Quantity");
 
                    // Update the line total.
                    CalculateLineTotal();
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int Special
        {
            get
            {
                return _special;
            }
            set
            {
                ReportPropertyChanging("Special");
                _special = value;
                ReportPropertyChanged("Special");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public int Product
        {
            get
            {
                return _product;
            }
            set
            {
                // Validate the value before setting it.
                if (value < 1)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidNegative, 
                              new string[2] { value.ToString(), "Product" }));
                }
                ReportPropertyChanging("Product");
                _product = value;
                ReportPropertyChanged("Product");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)] 
        public decimal Price
        {
            get
            {
                return _price;
            }
            set
            {
                if (_price != value)
                {
                    // Validate the value before setting it.
                    if (value < 0)
                    {
                        throw new ApplicationException(string.Format(
                                  Errors.propertyNotValidNegative,
                                  new string[2] { value.ToString(), "Price" }));
                    }

                    ReportPropertyChanging("Price");
                    _price = value;
                    ReportPropertyChanged("Price");

                    // Update the line total.
                    CalculateLineTotal();
                }
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public decimal Discount
        {
            get
            {
                return _discount;
            }
            set
            {
                // Validate the value before setting it.
                if (value < 0)
                {
                    throw new ApplicationException(string.Format(
                              Errors.propertyNotValidNegative,
                              new string[2] { value.ToString(), "Discount" }));
                }
                ReportPropertyChanging("Discount");
                _discount = value;
                ReportPropertyChanged("Discount");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public Guid RowGuid
        {
            get
            {
                return _rowGuid;
            }
            set
            {
                ReportPropertyChanging("RowGuid");
                _rowGuid = value;
                ReportPropertyChanged("RowGuid");
            }
        }
        [EdmScalarPropertyAttribute(IsNullable = false)]
        public DateTime ModifiedDate
        {
            get
            {
                return _modifiedDate;
            }
            set
            {
                ReportPropertyChanging("ModifiedDate");
                _modifiedDate = value;
                ReportPropertyChanged("ModifiedDate");
            }
        }
        public decimal Total
        {
            get
            {
                return _total;
            }
        }

        private void CalculateLineTotal()
        {
            _total = (_quantity * (_price - _discount)); 
        }
    }
    public class Errors
    {
        public const string propertyNotValidNegative =
            @"The value '{0}' for the {1} property is not valid. It cannot be a negative number or zero.";
        public const string propertyNotValidString =
            @"The value '{0}' for the {1} property is not valid.";
    }
}

See Also

Community Additions

Show: