Data Model Setup Problem

smcniel24 21 Reputation points
2021-06-10T18:25:11.103+00:00

I'm new to Blazor and I'm having a bit of a problem with my Data Access Layer Model. I created a database and I double checked all my keys and foreign keys to make sure they are correct. I imported the model (Reverser Engineer) using EF Core Power Tools but I can't seem to get my Models to connect via the FK's. For Example.

To keep it simple -

Company Table
ID - PK
CompanyName - varchar

Employee Table
ID - PK
Name - varchar

CompanyEmployee Table
ID - PK
CompanyID -FK
EmployeeID - FK

in my blazor c# code

@if(companyEmployees != null @@ companyEmployees .Count > 0)
{
    @foreach(var item in companyEmployees)
    {
        <h4>@item.Employee.Name</h4>  // < ---- ERROR HERE Because Employee is NULL
    }
}

@code
{
    List<CompanyEmployee> companyEmployees = null;

    protected override async Task OnInitializedAsync()
    {
         using(DbContext context = new DbContext())
         {
              companyEmployees = 
              await context.CompanyEmployee.Where(c => c.CompanyId == 1).ToListAsync();   // so get all the employee ID from the company that has the ID=1
         }
     }
}

where i commented above the error. I'm getting all the employee CompanyEmployee objects but the Employee object in my foreach statements are null. It's like the Foreign Keys aren't talking to each other.

Anyone have thoughts?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,404 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,312 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,196 Reputation points
    2021-06-10T18:48:34.683+00:00

    The following is working with EF Core 5.

    The relationships are defined in the DbContext class or if you elected to split out configurations each model is placed into a separate class.

    So let's say I have a Customer model that has a navigation (relationship) to ContactType model, in the customer configuration we would see the following setting up the relation between the two models.

    entity.HasOne(d => d.ContactTypeIdentifierNavigation)  
        .WithMany(p => p.Customers)  
        .HasForeignKey(d => d.ContactTypeIdentifier)  
        .HasConstraintName("FK_Customers_ContactType");  
    

    Then in the customer model you would have the following to collect data from the ContactType model

    public virtual ContactType ContactTypeIdentifierNavigation { get; set; }  
    

    I've use EF Power Tools for a while now and never had your issue. Now one way to verify everything is setup correctly, go into SQL-Server Management Studio, traverse to your database, right click on database diagram and if there are none, create one. A relationship done right looks like the following in regards to the case above, Customers ContactType. If the relationship is incorrect EF Core Power Tools does what it's told so this may be the issue.

    104363-figure1.png

    Finally, you need to indicate the navigation should be included e.g. (note the use of Include)

    using var context = new NorthwindContext();  
      
    Customers results = context.Customers  
        .Include(customer => customer.ContactTypeIdentifierNavigation)  
        .FirstOrDefault(customer => customer.CustomerIdentifier == 1);  
    

    Async version

    public static async Task<Customers> Demo()  
    {  
        await using var context = new NorthwindContext();  
      
        return await context.Customers  
            .Include(customer => customer.ContactTypeIdentifierNavigation)  
            .FirstOrDefaultAsync(customer => customer.CustomerIdentifier == 1);  
    }  
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-06-10T18:39:31.91+00:00

    Well you need to be doing some 'Includes' if you want to get any child objects to a given parent.

    https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx

    It doesn't matter what version of EF is being used 'Include" works the same there is also 'ThenInclude' too

    0 comments No comments

  2. smcniel24 21 Reputation points
    2021-06-10T20:59:59.213+00:00

    Great! Thank you so much for your responses. I have controller in my Business Layer and I simply needed to Include the table in my query.