Click here to Skip to main content
15,896,118 members
Articles / Web Development / ASP.NET

A Beginner's Tutorial for Understanding and Implementing Relationships using Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.71/5 (18 votes)
3 Feb 2013CPOL8 min read 53.9K   1.5K   57  
In this article we will try to see how we can model tables having one to many and many to many relationships using Entity Framework.
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;

[assembly: EdmSchemaAttribute()]
#region EDM Relationship Metadata

[assembly: EdmRelationshipAttribute("SampleDbModel", "FK_Assets_Rooms", "Rooms", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(SampleDbModel.Room), "Assets", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SampleDbModel.Asset), true)]
[assembly: EdmRelationshipAttribute("SampleDbModel", "ProjectRooms", "Project", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SampleDbModel.Project), "Room", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SampleDbModel.Room))]

#endregion

namespace SampleDbModel
{
    #region Contexts
    
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    public partial class SampleDbEntities : ObjectContext
    {
        #region Constructors
    
        /// <summary>
        /// Initializes a new SampleDbEntities object using the connection string found in the 'SampleDbEntities' section of the application configuration file.
        /// </summary>
        public SampleDbEntities() : base("name=SampleDbEntities", "SampleDbEntities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;
            OnContextCreated();
        }
    
        /// <summary>
        /// Initialize a new SampleDbEntities object.
        /// </summary>
        public SampleDbEntities(string connectionString) : base(connectionString, "SampleDbEntities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;
            OnContextCreated();
        }
    
        /// <summary>
        /// Initialize a new SampleDbEntities object.
        /// </summary>
        public SampleDbEntities(EntityConnection connection) : base(connection, "SampleDbEntities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;
            OnContextCreated();
        }
    
        #endregion
    
        #region Partial Methods
    
        partial void OnContextCreated();
    
        #endregion
    
        #region ObjectSet Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        public ObjectSet<Asset> Assets
        {
            get
            {
                if ((_Assets == null))
                {
                    _Assets = base.CreateObjectSet<Asset>("Assets");
                }
                return _Assets;
            }
        }
        private ObjectSet<Asset> _Assets;
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        public ObjectSet<Room> Rooms
        {
            get
            {
                if ((_Rooms == null))
                {
                    _Rooms = base.CreateObjectSet<Room>("Rooms");
                }
                return _Rooms;
            }
        }
        private ObjectSet<Room> _Rooms;
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        public ObjectSet<Project> Projects
        {
            get
            {
                if ((_Projects == null))
                {
                    _Projects = base.CreateObjectSet<Project>("Projects");
                }
                return _Projects;
            }
        }
        private ObjectSet<Project> _Projects;

        #endregion
        #region AddTo Methods
    
        /// <summary>
        /// Deprecated Method for adding a new object to the Assets EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
        /// </summary>
        public void AddToAssets(Asset asset)
        {
            base.AddObject("Assets", asset);
        }
    
        /// <summary>
        /// Deprecated Method for adding a new object to the Rooms EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
        /// </summary>
        public void AddToRooms(Room room)
        {
            base.AddObject("Rooms", room);
        }
    
        /// <summary>
        /// Deprecated Method for adding a new object to the Projects EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
        /// </summary>
        public void AddToProjects(Project project)
        {
            base.AddObject("Projects", project);
        }

        #endregion
    }
    

    #endregion
    
    #region Entities
    
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmEntityTypeAttribute(NamespaceName="SampleDbModel", Name="Asset")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Asset : EntityObject
    {
        #region Factory Method
    
        /// <summary>
        /// Create a new Asset object.
        /// </summary>
        /// <param name="assetID">Initial value of the AssetID property.</param>
        public static Asset CreateAsset(global::System.Int32 assetID)
        {
            Asset asset = new Asset();
            asset.AssetID = assetID;
            return asset;
        }

        #endregion
        #region Primitive Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.Int32 AssetID
        {
            get
            {
                return _AssetID;
            }
            set
            {
                if (_AssetID != value)
                {
                    OnAssetIDChanging(value);
                    ReportPropertyChanging("AssetID");
                    _AssetID = StructuralObject.SetValidValue(value);
                    ReportPropertyChanged("AssetID");
                    OnAssetIDChanged();
                }
            }
        }
        private global::System.Int32 _AssetID;
        partial void OnAssetIDChanging(global::System.Int32 value);
        partial void OnAssetIDChanged();
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String AssetName
        {
            get
            {
                return _AssetName;
            }
            set
            {
                OnAssetNameChanging(value);
                ReportPropertyChanging("AssetName");
                _AssetName = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("AssetName");
                OnAssetNameChanged();
            }
        }
        private global::System.String _AssetName;
        partial void OnAssetNameChanging(global::System.String value);
        partial void OnAssetNameChanged();
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public Nullable<global::System.Int32> RoomID
        {
            get
            {
                return _RoomID;
            }
            set
            {
                OnRoomIDChanging(value);
                ReportPropertyChanging("RoomID");
                _RoomID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("RoomID");
                OnRoomIDChanged();
            }
        }
        private Nullable<global::System.Int32> _RoomID;
        partial void OnRoomIDChanging(Nullable<global::System.Int32> value);
        partial void OnRoomIDChanged();

        #endregion
    
        #region Navigation Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [XmlIgnoreAttribute()]
        [SoapIgnoreAttribute()]
        [DataMemberAttribute()]
        [EdmRelationshipNavigationPropertyAttribute("SampleDbModel", "FK_Assets_Rooms", "Rooms")]
        public Room Room
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Room>("SampleDbModel.FK_Assets_Rooms", "Rooms").Value;
            }
            set
            {
                ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Room>("SampleDbModel.FK_Assets_Rooms", "Rooms").Value = value;
            }
        }
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [BrowsableAttribute(false)]
        [DataMemberAttribute()]
        public EntityReference<Room> RoomReference
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Room>("SampleDbModel.FK_Assets_Rooms", "Rooms");
            }
            set
            {
                if ((value != null))
                {
                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Room>("SampleDbModel.FK_Assets_Rooms", "Rooms", value);
                }
            }
        }

        #endregion
    }
    
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmEntityTypeAttribute(NamespaceName="SampleDbModel", Name="Project")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Project : EntityObject
    {
        #region Factory Method
    
        /// <summary>
        /// Create a new Project object.
        /// </summary>
        /// <param name="projectID">Initial value of the ProjectID property.</param>
        public static Project CreateProject(global::System.Int32 projectID)
        {
            Project project = new Project();
            project.ProjectID = projectID;
            return project;
        }

        #endregion
        #region Primitive Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.Int32 ProjectID
        {
            get
            {
                return _ProjectID;
            }
            set
            {
                if (_ProjectID != value)
                {
                    OnProjectIDChanging(value);
                    ReportPropertyChanging("ProjectID");
                    _ProjectID = StructuralObject.SetValidValue(value);
                    ReportPropertyChanged("ProjectID");
                    OnProjectIDChanged();
                }
            }
        }
        private global::System.Int32 _ProjectID;
        partial void OnProjectIDChanging(global::System.Int32 value);
        partial void OnProjectIDChanged();
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String ProjectName
        {
            get
            {
                return _ProjectName;
            }
            set
            {
                OnProjectNameChanging(value);
                ReportPropertyChanging("ProjectName");
                _ProjectName = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("ProjectName");
                OnProjectNameChanged();
            }
        }
        private global::System.String _ProjectName;
        partial void OnProjectNameChanging(global::System.String value);
        partial void OnProjectNameChanged();

        #endregion
    
        #region Navigation Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [XmlIgnoreAttribute()]
        [SoapIgnoreAttribute()]
        [DataMemberAttribute()]
        [EdmRelationshipNavigationPropertyAttribute("SampleDbModel", "ProjectRooms", "Room")]
        public EntityCollection<Room> Rooms
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Room>("SampleDbModel.ProjectRooms", "Room");
            }
            set
            {
                if ((value != null))
                {
                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Room>("SampleDbModel.ProjectRooms", "Room", value);
                }
            }
        }

        #endregion
    }
    
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmEntityTypeAttribute(NamespaceName="SampleDbModel", Name="Room")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Room : EntityObject
    {
        #region Factory Method
    
        /// <summary>
        /// Create a new Room object.
        /// </summary>
        /// <param name="roomID">Initial value of the RoomID property.</param>
        public static Room CreateRoom(global::System.Int32 roomID)
        {
            Room room = new Room();
            room.RoomID = roomID;
            return room;
        }

        #endregion
        #region Primitive Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.Int32 RoomID
        {
            get
            {
                return _RoomID;
            }
            set
            {
                if (_RoomID != value)
                {
                    OnRoomIDChanging(value);
                    ReportPropertyChanging("RoomID");
                    _RoomID = StructuralObject.SetValidValue(value);
                    ReportPropertyChanged("RoomID");
                    OnRoomIDChanged();
                }
            }
        }
        private global::System.Int32 _RoomID;
        partial void OnRoomIDChanging(global::System.Int32 value);
        partial void OnRoomIDChanged();
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String RoomName
        {
            get
            {
                return _RoomName;
            }
            set
            {
                OnRoomNameChanging(value);
                ReportPropertyChanging("RoomName");
                _RoomName = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("RoomName");
                OnRoomNameChanged();
            }
        }
        private global::System.String _RoomName;
        partial void OnRoomNameChanging(global::System.String value);
        partial void OnRoomNameChanged();

        #endregion
    
        #region Navigation Properties
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [XmlIgnoreAttribute()]
        [SoapIgnoreAttribute()]
        [DataMemberAttribute()]
        [EdmRelationshipNavigationPropertyAttribute("SampleDbModel", "FK_Assets_Rooms", "Assets")]
        public EntityCollection<Asset> Assets
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Asset>("SampleDbModel.FK_Assets_Rooms", "Assets");
            }
            set
            {
                if ((value != null))
                {
                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Asset>("SampleDbModel.FK_Assets_Rooms", "Assets", value);
                }
            }
        }
    
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [XmlIgnoreAttribute()]
        [SoapIgnoreAttribute()]
        [DataMemberAttribute()]
        [EdmRelationshipNavigationPropertyAttribute("SampleDbModel", "ProjectRooms", "Project")]
        public EntityCollection<Project> Projects
        {
            get
            {
                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Project>("SampleDbModel.ProjectRooms", "Project");
            }
            set
            {
                if ((value != null))
                {
                    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Project>("SampleDbModel.ProjectRooms", "Project", value);
                }
            }
        }

        #endregion
    }

    #endregion
    
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions