Foreign key column in ASP.NET Core Grid component
6 Dec 202424 minutes to read
The Foreign key column in the Syncfusion Grid component allows you to display related data from a foreign key data source in a column within the grid. This feature is particularly useful when you have a column in the grid that represents a foreign key relationship with another data source.
To enable and integrate the foreign key column in the ASP.NET Core Grid component, follow these steps:
- Define the foreign key column in the grid using the following properties:
-
dataSource
: Specifies the foreign data source that contains the related data. -
foreignKeyField
: Maps the column name in the grid to the field in the foreign data source that represents the foreign key relationship. -
foreignKeyValue
: Specifies the field from the foreign data source that should be displayed in the grid as the related data.
<e-grid-column field="EmployeeID" headerText="Employee ID" foreignKeyValue="FirstName" foreignKeyField="EmployeeID" dataSource="ViewBag.foreignData"></e-grid-column>
The
foreignKeyField
property should match the name of the field in the foreign data source that represents the foreign key relationship, and theforeignKeyValue
property should specify the field from the foreign data source that should be displayed in the grid as the related data.
Binding local data
The Syncfusion Grid component provides a convenient way to bind local data to a foreign key column. This allows you to display related data from a local data source within the grid. Here’s an example of how to bind local data to a Foreign Key column in Syncfusion Grid:
In this example, data is the local data source for the Grid, and employeeData is the local data source for the foreign key column. The field
property of the e-grid-column component is set to EmployeeID which represents the foreign key value in the data. The foreignKeyValue
property is set to FirstName which represents the field name in the employeeData that you want to display in the foreign key column.
<ejs-grid id="grid" dataSource="@ViewBag.dataSource" height="348px" >
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Employee Name" foreignKeyValue="FirstName" dataSource="ViewBag.foreignData" width="150"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.foreignData = EmployeeDetails.GetAllRecords();
return View();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EJ2CoreSampleBrowser.Models
{
public class EmployeeView
{
public EmployeeView()
{
}
public EmployeeView(int EmployeeID, string FirstName, string LastName, string Title, DateTime BirthDate, DateTime HireDate, int ReportsTo, string Address, string PostalCode, string Phone, string City, string Country)
{
this.EmployeeID = EmployeeID;
this.FirstName = FirstName;
this.LastName = LastName;
this.Title = Title;
this.BirthDate = BirthDate;
this.HireDate = HireDate;
this.ReportsTo = ReportsTo;
this.Address = Address;
this.PostalCode = PostalCode;
this.Phone = Phone;
this.City = City;
this.Country = Country;
}
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public DateTime BirthDate { get; set; }
public DateTime HireDate { get; set; }
public int ReportsTo { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string Phone { get; set; }
public string City { get; set; }
public string Country { get; set; }
public static List<EmployeeView> GetAllRecords()
{
List<EmployeeView> Emp = new List<Models.EmployeeView>();
Emp.Add(new EmployeeView(1, "Nancy", "Davolio", "Sales Representative", new DateTime(1948, 12, 08), new DateTime(1992, 05, 01), 2, "507 - 20th Ave. E.Apt. 2A ", " 98122", "(206) 555-9857 ", "Seattle ", "USA"));
Emp.Add(new EmployeeView(2, "Andrew", "Fuller", "Vice President, Sales", new DateTime(1952, 02, 19), new DateTime(1992, 08, 14), 4, "908 W. Capital Way", "98401 ", "(206) 555-9482 ", "Kirkland ", "USA"));
Emp.Add(new EmployeeView(3, "Janet", "Leverling", "Sales Representative", new DateTime(1963, 08, 30), new DateTime(1992, 04, 01), 3, " 4110 Old Redmond Rd.", "98052 ", "(206) 555-8122", "Redmond ", "USA "));
Emp.Add(new EmployeeView(4, "Margaret", "Peacock", "Sales Representative", new DateTime(1937, 09, 19), new DateTime(1993, 05, 03), 6, "14 Garrett Hill ", "SW1 8JR ", "(71) 555-4848 ", "London ", "UK "));
Emp.Add(new EmployeeView(5, "Steven", "Buchanan", "Sales Manager", new DateTime(1955, 03, 04), new DateTime(1993, 10, 17), 8, "Coventry HouseMiner Rd. ", "EC2 7JR ", " (206) 555-8122", "Tacoma ", " USA"));
Emp.Add(new EmployeeView(6, "Michael", "Suyama", "Sales Representative", new DateTime(1963, 07, 02), new DateTime(1993, 10, 17), 2, " 7 Houndstooth Rd.", " WG2 7LT", "(71) 555-4444 ", "London ", "UK "));
Emp.Add(new EmployeeView(7, "Robert", "King", "Sales Representative", new DateTime(1960, 05, 29), new DateTime(1994, 01, 02), 7, "Edgeham HollowWinchester Way ", "RG1 9SP ", "(71) 555-5598 ", "London ", " UK"));
Emp.Add(new EmployeeView(8, "Laura", "Callahan", "Inside Sales Coordinator", new DateTime(1958, 01, 09), new DateTime(1994, 03, 05), 9, "722 Moss Bay Blvd. ", "98033 ", " (206) 555-3412", "Seattle ", "USA "));
Emp.Add(new EmployeeView(9, "Anne", "Dodsworth", "Sales Representative", new DateTime(1966, 01, 27), new DateTime(1994, 11, 15), 5, "4726 - 11th Ave. N.E. ", "98105 ", "(71) 555-5598 ", " London", "UK "));
Emp.Add(new EmployeeView(10, "Albert", "Hellstrom", "Sales Manager", new DateTime(1956, 11, 13), new DateTime(1995, 01, 22), 3, "15 Maple Avenue", "11357", "(206) 555-1122", "Queens", "USA"));
Emp.Add(new EmployeeView(11, "Emma", "Jenkins", "Marketing Specialist", new DateTime(1972, 04, 15), new DateTime(1996, 07, 12), 4, "22 Willow Drive", "90210", "(213) 555-1212", "Beverly Hills", "USA"));
Emp.Add(new EmployeeView(12, "Samuel", "Green", "Product Manager", new DateTime(1980, 06, 24), new DateTime(1998, 09, 10), 6, "87 Elm Street", "60657", "(312) 555-9876", "Chicago", "USA"));
Emp.Add(new EmployeeView(13, "Sophia", "Brown", "Regional Manager", new DateTime(1968, 02, 10), new DateTime(1997, 03, 14), 7, "245 Oak Lane", "33101", "(305) 555-2233", "Miami", "USA"));
Emp.Add(new EmployeeView(14, "Liam", "Parker", "HR Specialist", new DateTime(1975, 09, 12), new DateTime(1999, 11, 18), 2, "19 Cedar Blvd", "78201", "(210) 555-3344", "San Antonio", "USA"));
Emp.Add(new EmployeeView(15, "Olivia", "Evans", "Sales Representative", new DateTime(1985, 03, 08), new DateTime(2001, 05, 09), 5, "67 Birch Road", "94123", "(415) 555-5566", "San Francisco", "USA"));
Emp.Add(new EmployeeView(16, "James", "Taylor", "Technical Lead", new DateTime(1979, 08, 20), new DateTime(2000, 02, 12), 8, "110 Maple Ave", "75201", "(214) 555-6677", "Dallas", "USA"));
Emp.Add(new EmployeeView(17, "Mia", "Clark", "Sales Coordinator", new DateTime(1990, 07, 11), new DateTime(2010, 06, 15), 9, "902 Pine Street", "10001", "(212) 555-7788", "New York", "USA"));
Emp.Add(new EmployeeView(18, "Benjamin", "Walker", "Accountant", new DateTime(1983, 11, 25), new DateTime(2005, 09, 21), 3, "35 Spruce Lane", "80203", "(303) 555-8899", "Denver", "USA"));
Emp.Add(new EmployeeView(19, "Charlotte", "Harris", "Chief Financial Officer", new DateTime(1971, 12, 05), new DateTime(1996, 10, 29), 10, "888 Elm Drive", "98101", "(206) 555-9900", "Seattle", "USA"));
Emp.Add(new EmployeeView(20, "Alexander", "Scott", "Software Engineer", new DateTime(1992, 05, 03), new DateTime(2018, 07, 17), 1, "12 Aspen Lane", "02139", "(617) 555-1020", "Cambridge", "USA"));
Emp.Add(new EmployeeView(21, "Evelyn", "Mitchell", "Marketing Manager", new DateTime(1988, 10, 19), new DateTime(2012, 04, 11), 6, "24 Fir Avenue", "85001", "(602) 555-2031", "Phoenix", "USA"));
Emp.Add(new EmployeeView(22, "Daniel", "Perez", "UX Designer", new DateTime(1991, 02, 14), new DateTime(2015, 08, 05), 2, "75 Walnut Drive", "30301", "(404) 555-3042", "Atlanta", "USA"));
Emp.Add(new EmployeeView(23, "Grace", "Diaz", "Operations Manager", new DateTime(1984, 12, 27), new DateTime(2008, 03, 19), 7, "33 Chestnut St", "78250", "(210) 555-4053", "San Antonio", "USA"));
Emp.Add(new EmployeeView(24, "Matthew", "Brooks", "Content Strategist", new DateTime(1986, 07, 15), new DateTime(2010, 09, 25), 4, "41 Maple Way", "90001", "(213) 555-5064", "Los Angeles", "USA"));
return Emp;
}
}
}
Binding remote data
The Foreign key column in Syncfusion Grid allows you to bind remote data for a foreign key column. You can assign the service data as an instance of DataManager
instead of using the dataSource
property, and provide the endpoint URL
as the data source URL.
This example demonstrates how to use the foreign key column with remote data binding using the ODataV4Adaptor in the grid:
<ejs-grid id="grid" height="348px">
<e-data-manager url="https://services.odata.org/V4/Northwind/Northwind.svc/Orders/" adaptor="ODataV4Adaptor"></e-data-manager>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Empolyee Name" foreignKeyField="EmployeeID" foreignKeyValue="FirstName" width="150">
<e-data-manager url="https://services.odata.org/V4/Northwind/Northwind.svc/Employees/" adaptor="ODataV4Adaptor">
</e-data-manager>
</e-grid-column>
<e-grid-column field="Freight" headerText="Freight" textAlign="Right" editType="numericedit" format="C2" width="120"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" editType="dropdownedit" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
- For remote data, the sorting and grouping is done based on
column.foreignKeyField
instead ofcolumn.foreignKeyValue
.- If
column.foreignKeyField
is not defined, then the column usescolumn.field
.
Use edit template in foreign key column
The Syncfusion Grid provides support for using an edit template in a foreign key column. By default, a dropdown component is used for editing foreign key column. However, you can render a different component for editing by using the column.edit
property. Here’s an example that demonstrates how to use an edit template in a foreign key column:
In this example, an AutoComplete component is rendered as the edit template for the “EmployeeID” foreign key column. The dataSource property of the AutoComplete component is set to the employees data, and the fields property is configured to display the “FirstName” field as the value.
<ejs-grid id="grid" dataSource="@ViewBag.dataSource" height="348px" toolbar="@(new List<string>() { "Edit","Cancel", "Update" })">
<e-grid-editSettings allowEditing="true"></e-grid-editSettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Employee Name" width="120" foreignKeyValue="FirstName" dataSource="ViewBag.foreignData" edit="@(new {create="create", read="read", destroy="destroy", write="write"})"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="Ship Country" width="150" editType='dropdownedit'></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
var autoComplete;
var employeeData = @Json.Serialize(ViewBag.foreignData);
function create() { // to create input element
return document.createElement('input');
}
function read () { // return edited value to update data source
var value = new ej.data.DataManager(employeeData).executeLocal(new ej.data.Query().where('FirstName', 'equal', autoComplete.value));
return value.length && value[0]['EmployeeID']; // to convert foreign key value to local value.
}
function destroy () { // to destroy the custom component.
autoComplete.destroy();
}
function write (args) { // to show the value for custom component
autoComplete = new ej.dropdowns.AutoComplete({
dataSource: employeeData,
fields: { value: args.column.foreignKeyValue },
value: args.foreignKeyData[0][args.column.foreignKeyValue]
});
autoComplete.appendTo(args.element);
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.foreignData = EmployeeDetails.GetAllRecords();
return View();
}
Customize filter UI of foreign key column
The Syncfusion Grid allows you to customize the filtering user interface (UI) for foreign key columns by using the column.filter
property. By default, a dropdown component is used for filtering foreign key columns. However, you can create your own custom filtering UI by specifying a template function for the column.filter
property. Here’s an example that demonstrates how to create a custom filtering UI in a foreign key column:
In this example, a DropDownList component is rendered as the filter UI for the “EmployeeID” foreign key column. The dataSource property of the DropDownList component is set to the employees data, and the fields property is configured to display the FirstName field as the text
and EmployeeID field as the value
. The value
property is set to the current filter value of the column.
<ejs-grid id="grid" dataSource="@ViewBag.dataSource" allowFiltering="true" height="348px">
<e-grid-filterSettings type="Menu"></e-grid-filterSettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Employee Name" width="150" foreignKeyValue="FirstName" dataSource="ViewBag.foreignData"
filter="@(new { ui = new { create = "create", read = "read", write = "write"} })"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format="C2" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
var dropInstance;
var employeeData = @Json.Serialize(ViewBag.foreignData);
function create (args) {
var filterInputElement = document.createElement('input');
filterInputElement.classList.add('filter-input');
args.target.appendChild(filterInputElement);
dropInstance = new ej.dropdowns.DropDownList({
dataSource: new ej.data.DataManager(employeeData),
fields: { text: 'FirstName', value: 'EmployeeID' },
placeholder: 'Select a value',
popupHeight: '200px'
});
dropInstance.appendTo(filterInputElement);
}
function write (args){
dropInstance.text = args.filteredValue || '';
}
function read (args) {
args.fltrObj.filterByColumn(args.column.field, args.operator, dropInstance.text);
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.foreignData = EmployeeDetails.GetAllRecords();
return View();
}
Use filter bar template in foreign key column
You can use the filter bar template in a foreign key column in Grid by defining the column.filterBarTemplate
property. This allows you to customize the filter bar for the foreign key column with a custom component or HTML template. Here’s an example that demonstrates how to use a filter bar template in a foreign key column:
In this example, the “EmployeeID” column is a foreign key column, and the filter function is used as the filter bar template for this column. The filter
function can be defined in your component code and should return the desired component or HTML template for the filter bar. The column header shows the custom filter bar template and you can select filter value by using the DropDown options.
@{
Object filterTemplate = new Object();
filterTemplate = (new { read = "read", write = "write" });
}
<ejs-grid id="grid" dataSource="@ViewBag.dataSource" allowFiltering="true" height="348px">
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Employee Name" ForeignKeyField="EmployeeID" foreignKeyValue='FirstName' dataSource="ViewBag.foreignData" width="150" filterBarTemplate="filterTemplate"></e-grid-column>
<e-grid-column field="OrderDate" headerText="OrderDate" format="yMd" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format="C2" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="ShipCountry" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script>
function create (args) {
return document.createElement('input', { className: 'filter-input' });
}
function write (args) {
var employeeData = @Json.Serialize(ViewBag.foreignData);
employeeData.splice(0, 0, { 'FirstName': 'All' }); // for clear filtering
var dropInstance = new ej.dropdowns.DropDownList({
dataSource: new ej.data.DataManager(employeeData),
fields: { text: 'FirstName' },
placeholder: 'Select a value',
popupHeight: '200px',
index: 0,
change: (args) => {
var grid = document.getElementById("grid").ej2_instances[0];
if (args.value !== 'All') {
grid.filterByColumn('EmployeeID', 'equal', args.value);
}
else {
grid.clearFiltering(['EmployeeID']);
}
}
});
dropInstance.appendTo(args.element);
}
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.foreignData = EmployeeDetails.GetAllRecords();
return View();
}
Perform aggregation in foreign key column
By default, aggregations are not supported in a foreign key column in the Syncfusion Grid. However, you can achieve aggregation for a foreign key column by using customAggregate
.
To perform aggregation in a foreign key column, follow these steps:
1.Define a foreign key column in the Grid.
2.Implement a custom aggregate function to calculate the aggregation for the foreign key column.
3.Set the customAggregate
property of the column to the custom aggregate function.
Here’s an example that demonstrates how to perform aggregation in a foreign key column:
In the provided example, the customAggregateFn
function is used to filter the data based on the FirstName field of the foreign key column, using the getForeignData
internal function. The function then counts the occurrences of Margaret. The result is displayed in the grid’s footer template using the ng-template with the footerTemplate
reference.
<ejs-grid id="grid" dataSource="@ViewBag.dataSource" height="348px">
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Employee Name" width="120" foreignKeyValue='FirstName' dataSource="ViewBag.foreignData"></e-grid-column>
<e-grid-column field="OrderDate" headerText="OrderDate" format="yMd" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format="C2" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="ShipCountry" headerText="ShipCountry" width="150"></e-grid-column>
</e-grid-columns>
<e-grid-aggregates>
<e-grid-aggregate>
<e-aggregate-columns>
<e-aggregate-column field="EmployeeID" type="Custom" customAggregate="@("customAggregateFunction")" footerTemplate="Count of Margaret:${Custom}"></e-aggregate-column>
</e-aggregate-columns>
</e-grid-aggregate>
</e-grid-aggregates>
</ejs-grid>
<script>
function customAggregateFunction(data, column) {
var grid = document.getElementById("grid").ej2_instances[0];
return data.result.filter(function (employeeRecord) {
return ej.base.getValue('FirstName', ej.grids.getForeignData(grid.getColumnByField(column.columnName), employeeRecord)[0]) === 'Margaret';
}).length;
};
</script>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.foreignData = EmployeeDetails.GetAllRecords();
return View();
}
Enable multiple foreign key columns
The Syncfusion Grid component supports the feature of enabling multiple foreign key columns with editing options. This allows users to display columns from foreign data sources in the Grid component.
In the following example, Customer Name and Ship City are foreign key columns that display the ContactName and City columns from foreign data.
<ejs-grid id="grid" dataSource="ViewBag.dataSource" height="348px" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })">
<e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editSettings>
<e-grid-columns>
<e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
<e-grid-column field="CustomerID" headerText="Customer Name" foreignKeyField="CustomerID" foreignKeyValue="ContactName" dataSource="ViewBag.customerData" width="150"></e-grid-column>
<e-grid-column field="Freight" headerText="Freight" format="C2" editType="numericedit" textAlign="Right" width="100"></e-grid-column>
<e-grid-column field="EmployeeID" headerText="Ship City" foreignKeyField="EmployeeID" foreignKeyValue="City" dataSource="ViewBag.employeeData" width="150"></e-grid-column>
<e-grid-column field="ShipName" headerText="Ship Name" editType='dropdownedit' width="180"></e-grid-column>
</e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
ViewBag.dataSource = OrderDetails.GetAllRecords();
ViewBag.customerData = CustomerDetails.GetAllRecords();
ViewBag.employeeData = EmployeeDetails.GetAllRecords();
return View();
}