Set a One-to-Many Relationship (EF 6)

  • 3 minutes to read

In this lesson, you will learn how to set a one-to-many relationship between business objects. The Contact and Department business objects will be related by a one-to-many relationship. You will then learn the basics of automatic user interface construction for referenced objects.

  • Add the Department class as shown in the Inherit from the Business Class Library Class (EF 6) lesson. Replace the auto-generated code with the following.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using DevExpress.Persistent.Base;
    namespace MySolution.Module.BusinessObjects {
        public class Department {
            public Int32 ID { get; protected set; }
            public String Title { get; set; }
            public String Office { get; set; }
  • Register the Department class in DbContext. Edit the BusinessObjects\MySolutionDbContext.cs file as shown below.

    public class MySolutionDbContext : DbContext {
        public DbSet<Department> Departments { get; set; }
  • To implement the “One” part of the Department-Contact relationship, add a virtual Department property to the Contact class.

    public class Contact : Person {
        public virtual Department Department { get; set; } 
  • To implement the “Many” part of the Department-Contact relationship, add the Contacts property to the Department class and initialize it in the constructor.

    public class Department {
        public Department() {
            Contacts = new List<Contact>();
        public virtual IList<Contact> Contacts { get; set; }
  • Run the WinForms or ASP.NET application. Invoke a Detail View for a Department object. You can see the Contacts group. To add objects to the Contacts collection, use the New (button_new) or Link (link_btn) button in this tab. The Link button allows you to add references to existing Contact objects.


    To remove a reference to an object from this collection, use the Unlink (unlink_img) button.


If you create a new Department and then create a new Contact in the Contacts collection, an associated Department is not immediately visible in the Detail View of the newly created Contact. The link between these objects is added later, when you save the Contact. You can change this behavior using the XafApplication.LinkNewObjectToParentImmediately property. When it is set to true, the link will be created and saved immediately after you click New.

You can see the code demonstrated in this lesson in the MySolution.Module | Data | Contact.cs (Contact.vb) and Department.cs (Department.vb) files of the EF Demo (Code First) installed with XAF. By default, the EF Demo (Code First) application is installed in %PUBLIC%\Documents\DevExpress Demos 20.2\Components.NET Core Desktop Libraries\eXpressApp Framework\EFDemoCodeFirst.


Next Lesson: Initialize a Property After Creating an Object (EF 6)

See Also