Breeze automatically filters out entities with a null foreign key when they are being expanded

I'm facing a situation where an entity in my database has a foreign key with a null value.

Upon expanding via JavaScript or Including in EF, I noticed that the rows containing the null foreign key are omitted.

Here's the SQL setup:

CREATE TABLE Entity
(
    Id BIGINT NOT NULL PRIMARY KEY
);

CREATE TABLE EntityType
(
    Id BIGINT IDENTITY NOT NULL PRIMARY KEY,
    EntityId BIGINT NULL REFERENCES Entity(Id)
);

INSERT INTO Entity(Id) VALUES (0);
INSERT INTO Entity(Id) VALUES (1);

INSERT INTO EntityType(EntityId) VALUES (0);
INSERT INTO EntityType(EntityId) VALUES (1);
INSERT INTO EntityType(EntityId) VALUES (NULL);

And here is the C# code:

public class Entity
{
    public long Id { get; set; }
}

public class EntityType
{
    public long Id { get; set; }
    public long EntityId { get; set; }
    public Entity Entity { get; set; }
}

public class EntityMap : EntityTypeConfiguration<Entity>
{
    public EntityMap()
    {
        HasKey(t => t.Id);
    }
}

public class EntityTypeMap : EntityTypeConfiguration<EntityType>
{
    public EntityTypeMap()
    {
        HasKey(t => t.Id);

        HasRequired(t => t.Entity)
           .WithMany()
           .HasForeignKey(t => t.EntityId);
    }
}

[BreezeController]
public class EntityController : ApiController
{
    private readonly EFContextProvider<EntityContext> _contextProvider =
        new EFContextProvider<EntityContext>();

    [HttpGet]
    public IQueryable<Entity> Entities()
    {
        return _contextProvider.Context.Entities;
    }

    [HttpGet]
    public IQueryable<EntityType> EntityType()
    {
        return _contextProvider.Context.EntityTypes;
    }
}

Additionally, this is the JavaScript snippet:

angular.module('App').factory('EntityTypeService', function(serviceBase) {
    function getAll {
        return serviceBase.manager.executeQuery(
            serviceBase.query.
                from('EntityTypes').
                expand('Entity')
        ).to$q();
    }

    return {
        getAll: getAll
    };
});

angular.module('App').controller('HomeCtrl', function($scope, EntityTypeService) {
    EntityTypeService.getAll().then(function(data) {
        $scope.entityTypes = data.results;
    });
});

While inspecting $scope.entityTypes, only rows with a non-null EntityId appear to be present.

Answer №1

After investigating, it was discovered that the issue lied in a copy-pasting error related to EF.

The corrected mapping should utilize HasOptional instead of HasRequired.

public class EntityTypeMap : EntityTypeConfiguration<EntityType>
{
    public EntityTypeMap()
    {
        HasKey(t => t.Id);

        HasOptional(t => t.Entity)
           .WithMany()
           .HasForeignKey(t => t.EntityId);
    }
}

Following this modification will fetch all rows of EntityType.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using AngularJS 1 to create a universal search filter for all values stored in an Array or JSON object

I am currently working with an outdated version of AngularJS (1.x). I have a JSON object containing various key/value pairs. Is there a way to filter based on any of the values in the array? I am looking to implement a global search input field where users ...

Tips for customizing the appearance of popup windows

I want to enhance the appearance of my popup window by applying a different format for opening it. How can I style it so that it looks visually appealing when the popup window opens? You can find below the source code I am working with: HTML: <div onM ...

Extract data from an array in MongoDB by organizing it into sections based on dates

As a beginner in the world of MongoDB, I'm trying to figure out how to extract data from an array in separate sections. { "name":"User name", "messages":[ { "message":"Message 1", ...

Tips for integrating NPM Modules with Flask

As I deploy my Python application with Flask using the render_template() function onto a webpage, I am also attempting to integrate some JavaScript modules using npm. Even though I have installed the necessary modules in the static folder along with all my ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

The type 'typeof' does not contain a property called 'utm'

Currently, I am working on the front-end development of a project using Angular 10. As part of the project, I am utilizing Leaflet to showcase maps. However, there arose a necessity to install the dependency (leaflet.utm). The challenge I faced was distin ...

The column must have a defined value and cannot be left empty

I encountered an issue while trying to populate a database with seed data. The error message I received is: name: 'SequelizeDatabaseError', parent: Error: Column 'id' cannot be null code: 'ER_BAD_NULL_ERROR', errno: 1048, sql ...

Vuex bombards with errors without any clear explanation during commit

Within my Plugin, I am faced with the following code snippet: import firebase from 'firebase' export default context => { firebase.auth().onAuthStateChanged(userObject => { // eslint-disable-next-line no-console console.log({ us ...

Executing 10 lengthy functions in a repetitive manner at scheduled intervals while ensuring they do not run simultaneously

I am currently developing a .NET core worker service that will execute 10 distinct long-running functions responsible for parsing various CSV files and spreadsheets. My requirement is to schedule each function to run at different times throughout the day, ...

Learn how to efficiently print data from an object in AngularJS without repetition

My objective is to display an object using ng-repeat while taking into account that some keys are duplicated. I would like the duplicate keys to be displayed only once, and for the average of their similar values to be calculated. Here is the data: [ ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

What is the method for selecting an element using CSS code in Protractor?

Having trouble clicking on the element with CSS Selector: <button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view"> <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i> </button> This is what I've t ...

Run a section of code located in a different file

I have defined some global functions in main.js like this: Vue.prototype._isMobile = function () { return $(window).width() < 768 } //Few more similar functions Now, I want to move these functions to a separate file called util.js: return (function ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

What methods can be utilized in JavaScript to replicate the functionality of the CSS attr() function?

Is there a way to mimic the functionality of the attr() function in JavaScript? Specifically, I want to adjust the indentation of a paragraph based on the value of data-indent, similar to how we use p { text-indent: attr(data-indent em) }. <p data-inden ...

Unique loading of images without duplication

Hello everyone! I came across a script that loads images sequentially into my div element. It's working well, but I'd like to make it load random images without repeating any until all have been shown. As a newbie in this area, I've made so ...

Leveraging Node.js to efficiently handle large Excel files within a SAP S/4HANA application

I am seeking assistance with a challenge I am currently facing (please note that I am not a JavaScript developer). Any help would be greatly appreciated. Procedure: The user uploads an Excel file from the UI. In the backend, we utilize xlsx/exceljs Java ...

Node.js's module-only scope concept allows variables and functions defined within

Currently, I am attempting to create a function that can set a variable at the top-level scope of a module without it leaking into the global scope. Initially, I believed that implicit variable declarations within a module would remain confined to the modu ...

Converting Revit coordinates to Viewer format

Is there a way to translate estimated coordinates from a Revit model into Viewer coordinates in order to accurately place a three.js object within the Viewer? ...