Many-to-many relationship in EF user instance is NULL [duplicate] - c#

This question already has answers here:
EF Core returns null relations until direct access
(2 answers)
Closed 5 years ago.
I'm using .net core 2 mvc, I tried to build many-to-many relationship between Users and Steps.
the relationship is doen but when I query for the record I get user = null.
Hier is my code:
(applicationUser model):
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public List<StepsUsers> StepUser { get; set; }
}
(Steps model):
public class Steps
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<StepsUsers> StepUser { get; set; }
}
StepsUsers model:
public class StepsUsers : IAuditable
{
public int StepId { get; set; }
public Steps Step { get; set; }
public string UserId { get; set; }
public ApplicationUser User { get; set; }
}
In DbContext I did this :
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<StepsUsers>()
.HasKey(s => new { s.StepId, s.UserId });
builder.Entity<StepsUsers>()
.HasOne(su => su.Step)
.WithMany(s => s.StepUser)
.HasForeignKey(su => su.StepId);
builder.Entity<StepsUsers>()
.HasOne(su => su.User)
.WithMany(s => s.StepUser)
.HasForeignKey(su => su.UserId);
}
public DbSet<MyApp.Models.StepsUsers> StepsUsers { get; set; }
Now, when I query for an instance of StepsUsers with specific StepId I get all de fields correct except the User field is null
var stepUsers = await _context.StepsUsers.Where(s => s.StepId == id).ToListAsync();
I did the same code for another two tables and it works fine, I don't know why it is like this, any suggestion 1?

The cause of your problems is that your forgot to declare your To-many relations as virtual. Another improvement would be to declare them as virtual ICollection instead of List. After all, what would ApplicationUser.StepUser[4] mean?
If you configure a many-to-many relationship according to the entity framework conventions for many-to-many, you don't need to mention the junction table (StepsUsers). Entity framework will recognize the many-to-many and will create the junction table for you. If you stick to the code first conventions you won't even need the fluent API to configure the many-to-many.
In your design every ApplicationUser has zero or more Steps and every Step is done by zero or more ApplicationUsers.
class ApplicationUser
{
public int Id {get; set;}
// every ApplicationUser has zero or more Steps:
public virtual ICollection<Step> Steps {get; set;}
public string Name {get; set;}
...
}
class Step
{
public int Id {get; set;}
// every Step is performed by zero or more ApplicationUsers:
public virtual ICollection<ApplicationUser> ApplicationUsers {get; set;}
public string Name {get; set;}
...
}
public MyDbContext : DbContext
{
public DbSet<ApplicationUser ApplictionUsers {get; set;}
public DbSet<Step> Steps {get; set;}
}
This is all entity framework needs to know to recognize that you configured a many-to-many relationship. Entity framework will create the junction table for you and the foreign keys to the junction table. You don't need to declare the junction table.
But how am I suppose to do a join if I don't have the junction table?
The answer is: Don't do the join. Use the collections instead.
If you want all ApplicationUsers that ... with all their Steps that ... you would normally do an inner join with the junction table, and do some group by to get the Application users. Ever tried method syntax to join three tables? They look hideous, difficult to understand, error prone and difficult to maintain.
Using the collections in entity framework your query would be much simpler:
var result = myDbContext.ApplicationUsers
.Where(applicationUser => applicationUser.Name == ...)
.Select(applicationUser => new
{
// select only the properties you plan to use:
Name = applicationUser.Name,
Steps = applicationUser.Steps
.Where(step => step.Name == ...)
.Select(step => new
{
// again fetch only Step properties you plan to use
Name = step.Name,
...
})
.ToList(),
});
Entity framework will recognize that joins with the junction table is needed and perform them for you.
If you want Steps that ... with their ApplicationUsers who ... you'll do something similar:
var result = myDbContext.Steps
.Where(step => ...)
.Select(step => new
{
Name = step.Name,
... // other properties
ApplicationUsers = step.ApplicationUsers
.Where(applicationUser => ...)
.Select(applicationUser => new
{
...
})
.ToList(),
});
In my experience, whenever I think of performing a query with a of DbSets using entity framework, whether it is in a many-to-many, a one-to-many or a one-to-one relation, the query can almost always be created using the collections instead of a join. They look simpler, they are better to understand and thus better to maintain.

Related

EF Core - how to model relation of Grandparent - Parent - Child on same model

Imagine a model of User that can have Parents and also can have Children.
How would you model such a case in EF Core?
I tried with something like that (pseudo-code)
public class User
{
public ICollection<Relation> Relations {get;set;}
public ICollection<User> Parents => Relation.Where(r => r.Relation == 'Parents')
public ICollection<User> Children => Relation.Where(r => r.Relation == 'Children')
}
public class Relaction
{
public User User1 {get;set;}
public Guid User1Id {get;set;}
public User User2 {get;set;}
public Guid User2Id {get;set;}
public Relation Relation {get;set;} //some enum or sth to indicate relation type
}
But in such modeling, I'm not able to force EF DbContext to fetch into User.Relations data where UserId is in User1Id and in User2Id.
Any idea?
What you are asking for is a classic many-to-many self relationship - (1) user as parent can have many users as children, and (2) user as child can have many users as parents.
Thus it is modelled with one main entity and one join (linking) entity similar to what you have shown. The linking entity does not need special indicator because the two FKs determine the role. i.e. lets change your example with more descriptive names:
public class User
{
public Guid Id { get; set; }
}
public class UserRelation
{
public User Parent { get; set; }
public User Child { get; set; }
public Guid ParentId { get; set; }
public Guid ChildId { get; set; }
}
Now, in pseudo code, given User user, then
user.Parents = db.Users.Where(u => user == u.Child)
user.Children = db.Users.Where(u => user == u.Parent)
EF Core 5.0+ allows you to hide the join entity (it still exists, but is maintained implicitly) and model the relationship with the so called skip navigations, which are the natural OO way of representing such relationship, e.g. the model becomes simply
public class User
{
public Guid Id { get; }
public ICollection<User> Parents { get; set; }
public ICollection<User> Children { get; set; }
}
This is all needed to create such relationship.
However the name of the join table and its columns by convention won't be what normally you would do - in this case, they would be "UserUser" table with "ParentsId" and "ChildrenId" columns.
If you use migrations and don't care about the names, then you are done and can safely skip the rest.
If you do care though, luckily EF Core allows you to change the defaults with fluent configuration (even though in a not so intuitive way):
modelBuilder.Entity<User>()
.HasMany(e => e.Parents)
.WithMany(e => e.Children)
.UsingEntity<Dictionary<string, object>>("UserRelation",
je => je.HasOne<User>().WithMany()
.HasForeignKey("ParentId").IsRequired().OnDelete(DeleteBehavior.Restrict),
je => je.HasOne<User>().WithMany()
.HasForeignKey("ChildId").IsRequired().OnDelete(DeleteBehavior.Restrict),
je => je.ToTable("UserRelations")
.HasKey("ParentId", "ChildId")
);
Here Dictionary<string, object> is the shared type EF Core will use to maintain the join entity in memory (change tracker). And is the most annoying thing in the above configuration since in a future they might change their minds and use different type (there are actually plans to do that in EF Core 6.0), so you'll have to update your mappings. Note that this does not affect the database design, just the memory storage type in EF Core change tracker.
So, because of that and the fact that in some scenarios it is better to work directly with the join entity, you could actually combine both approaches (explicit join entity and skip navigations) and get the best of both worlds.
To do than, you add the explicit entity and (optionally) navigations from/to it. The next is w/o collection navigations from User to UserRelation (with fully defined navigation you would need two ICollection<UserRelation> properties there):
public class User
{
public Guid Id { get; }
public ICollection<User> Parents { get; set; }
public ICollection<User> Children { get; set; }
}
public class UserRelation
{
public User Parent { get; set; }
public User Child { get; set; }
public Guid ParentId { get; set; }
public Guid ChildId { get; set; }
}
and required minimal fluent configuration
modelBuilder.Entity<User>()
.HasMany(e => e.Parents)
.WithMany(e => e.Children)
.UsingEntity<UserRelation>(
je => je.HasOne(e => e.Parent).WithMany(), // <-- here you would specify the corresponding collection nav property when exists
je => je.HasOne(e => e.Child).WithMany(), // <-- here you would specify the corresponding collection nav property when exists
je => je.ToTable("UserRelations")
);
The result is the same database model, but with different in-memory representation of the join entity and ability to query/manipulate it directly. Actually you can do the same with implicit entity, but in type unsafe way using sting names and object values which need to be cast to the appropriate type. This probably will improve in the future if they replace Dictionary<string, object> with some generic type, but for now explicit entity combined with skip navigations looks the best.
You can find (I guess better than mine) explanation of all this in the official EF Core documentation - Many-to-many and the whole Relationships section in general.

Mapping To a Single Lookup Table For Multiple Tables in EF Core

I'm attempting to map to a lookup table that contains values for multiple tables. I cannot modify the database. The table has a one-to-many relationship with multiple tables, but no foreign key constraints. The lookup table has three columns code, category and description. A sample set of the data would look like this:
Lookup table:
code
category
description
1
Role
Admin
2
Role
User
1
Job
Mechanic
2
Job
Plumber
3
Job
Electrician
1
Activity
Work
2
Activity
Overtime
3
Activity
Training
I'm interested in joining the Activity table that looks like this (some columns omitted for clarity):
Activity table:
id
code
hours
1
1
8.0
2
1
8.0
3
2
1.0
4
2
5.3
I want to join the Activity table to the Lookup table using EF Core. If I was writing a SQL statement I'd just have something like this:
SELECT *
FROM Activity
JOIN Lookup ON Lookup.code = Activity.code
AND Lookup.category = 'Activity'
So in EF Core I created my classes to represent my tables:
public class Lookup
{
[Key]
public string Code { get; set; }
public string Category { get; set; }
public string Description { get; set; }
}
public class Activity
{
[Key]
public string Id { get; set; }
public string Code { get; set; }
public double Hours { get; set; }
[NotMapped]
public string LookupCategory { get; set; } = "Activity";
public Lookup ActivityType { get; set; }
}
I also have the following fluent relationship setup:
modelBuilder.Entity<Activity>()
.HasOne<Lookup>(x => x.ActivityType)
.WithMany()
.HasForeignKey(x => x.Code);
But this doesn't work since there are multiple rows with the same code value. How do I get the key constraint to also take in to account the LookupCategory value since it is not mapped?
Following pjs's suggestions I was able to implement the following successfully:
I created a new class that extended Lookup. This class has the attribute NotMapped, which was an important part in getting everything to finally work.
[NotMapped]
public class ActivityType : StaffLookup{ }
In Activity I modified the class to use ActivityType instead of StaffLookup. I also removed the LookupCategory property
public class Activity
{
[Key]
public string Id { get; set; }
public string Code { get; set; }
public double Hours { get; set; }
// This is mapped to our subclass so that we can get the filtered values
public ActivityType ActivityType { get; set; }
}
In my OnModelCreating I removed the existing fluent relationship and added the following new ones:
// This tells EF what column is used as a the filter
modelBuilder.Entity<StaffLookup>()
.HasDiscriminator(x => x.Category);
// This is what filters the Lookup table for us
modelBuilder.Entity<ActivityType>()
.HasDiscriminator()
.HasValue("Activity");
// Since the foreign key isn't mapped in the database
// we need to add this relationship
modelBuilder.Entity<ActivityMain>()
.HasOne(x => x.ActivityType)
.WithMany()
.HasForeignKey(x => x.ActivityCode);
Look at setting up a Table-Per-Hierarchy, TPH, with Category as the discriminator. Then your EF model can have Lookup as the base table, with RoleType, ActivityType, etc. as child entities in your EF model. The relationship would be from ActivityType to Activity, and EF would already know that the only applicable values in ActivityType are the Lookup rows with Category = 'Activity'. You would want to verify all existing data meets those constraints since they aren't enforced in the database.

C# & Entity Framework Core creating entity many to many relation with itself as multiple parents and multiple children

I'm a relatively new programmer and I'm in the middle of creating Entities for Entity Framework Core for a project I'm currently on, but I'm having difficulty figuring out how to setup 1 specific entity named "Group".
The "Group" entity can contain zero to more groups as parents of it, and it can contain zero to more groups as its children.
i tried writing it the following way with the group class:
public class Group
{
public int GroupID { get; set; }
//Other properties here
public ICollection<SubGroup>? ParentGroups { get; set; }
public ICollection<SubGroup>? ChildGroups { get; set; }
}
with the SubGroup class looking like this:
public class SubGroup
{
public int ParentGroupID { get; set; }
public int ChildGroupID { get; set; }
public Group ParentGroup { get; set; }
public Group ChildGroup { get; set; }
}
alongside this piece of fluent API:
modelBuilder.Entity<SubGroup>().HasKey(sg => new { sg.ParentGroupID, sg.ChildGroupID });
modelBuilder.Entity<Group>().HasMany(g => g.ParentGroups).WithOne(sg => sg.ParentGroup).HasForeignKey(g => g.ParentGroupID).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Group>().HasMany(g => g.ChildGroups).WithOne(sg => sg.ChildGroup).HasForeignKey(g => g.ChildGroupID).OnDelete(DeleteBehavior.Restrict);
The thought process in my head is that subgroups should show which groups are children/parents of which groups.
While i was able to generate a migration and update the database, i'm not entirely sure if this is how you're supposed to do it, so i've also thought about doing it the following way:
public class Group
{
public int GroupID { get; set; }
//Other properties here
public ICollection<Group>? ParentGroups { get; set; }
public ICollection<Group>? ChildGroups { get; set; }
}
alongside the following fluent API:
modelBuilder.Entity<Group>().HasMany(g => g.ChildGroups).WithMany(sg => sg.ParentGroups);
i want to ask anyone who's made this kind of relation before if i'm right or wrong in either case, and how it should be written. I hope anyone could help me here
Thanks in advance
EDIT: I completely forgot to mention in the first case that the only reason I could update the database there was because I added .OnDelete(DeleteBehavior.Restrict) to the end of the fluent API because it kept warning me with this:
Introducing FOREIGN KEY constraint 'FK_SubGroup_Group_ParentGroupID' on table 'SubGroup' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints
I want the group table rows to cascade and delete all subgroup relation rows associated with the deleted group without deleting the other end of the relation but don't know how in this case

How to model a collection of items where one of them is the active item?

I have a situation where an entity has a list of children that are inactive. Additionally, they have another "current/active" sub entity of the same type.
The following would be the ideal modeling, but I cannot figure out how to this with Entity Framework Core:
public class Customer
{
public Application CurrentApplication { get; set; }
public List<Application> PastApplications { get; set; }
}
public class Application
{
public bool IsCurrent { get; set; }
public Customer Customer { get; set; }
}
In the past, I've typically modeled it as so:
public class Customer
{
public Application CurrentApplication => AllApplications.Single(a => a.IsCurrent);
public List<Application> PastApplications => AllApplications.Where(a => !a.IsCurrent);
public List<Application> AllApplications { get; set; }
}
public class Application
{
public bool IsCurrent { get; set; }
public Customer Customer { get; set; }
}
However, I feel that this could lead to the possibility of another Application incorrectly being set as IsCurrent, thus breaking the .Single().
What's the suggested way to accomplish this from a DDD perspective? If that doesn't match up with what EF Core can do, what is a good practical suggestion?
I don't think that this is a DDD problem, rather a how to design a relational DB model and how to use EF Core question.
First you need to decide what is the relationship between Customers and Applications:
One-to-Many, that is, a Customer may have zero or more Applications, but an Application belongs to exactly one Customer. This scenerio is also called a master-detail relationship. The entity on the Many side (Application in this case) stores a reference (called a foreign key) to its owner (Customer).
Many-to-Many, that is, a Customer may have zero or more Applications, but an Application may belong to zero or more Customers, as well. This scenario is modelled using an extra "join" table (usually named something like CustomerApplication) so the problem is resolved to two One-to-May relationships in the end.
If there is only one active Application at a given time (per customer), the active application can be modelled using a One-to-One (Zero-to-One, to be precise) relationship between Customer and Application (with a foreign key on Customer's side). It can also be modelled using a flag field on Application as you tried but that's not as error-proof as a foreign key (but may have better performance, though).
The code you posted resembles rather a One-to-Many scenario, so I show an example for that case. Understanding the following, you can easily change it Many-to-Many if desired.
First let's define the entities:
public class Customer
{
public int Id { get; set; }
public int? CurrentApplicationId { get; set; }
public Application CurrentApplication { get; set; }
public ICollection<Application> Applications { get; set; }
}
public class Application
{
public int Id { get; set; }
public Customer Customer { get; set; }
}
The single interesting part is int? CurrentApplicationId. We need to explicitly define the foreign key for our Zero-to-Many relationship (more on this later). The nullable int (int?) tells EF that this field can be NULL.
EF is usually able to figure out the relationship mappings but in this case we need to explain them to it explicitly:
class DataContext : DbContext
{
// ctor omitted for brevity
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(customer =>
{
customer.HasMany(entity => entity.Applications)
.WithOne(relatedEntity => relatedEntity.Customer)
.OnDelete(DeleteBehavior.Cascade);
customer.HasOne(entity => entity.CurrentApplication)
.WithOne()
.HasForeignKey<Customer>(entity => entity.CurrentApplicationId);
});
}
public DbSet<Application> Applications { get; set; }
public DbSet<Customer> Customers { get; set; }
}
What's going on in the OnModelCreating method is called fluent API configuration. This topic and conventions is a must to understand and control how EF maps the entities to DB tables.
Based on the mapping EF is able to generate (see code-first migrations) the following DB schema:
CREATE TABLE [Customers] (
[Id] INTEGER NOT NULL
, [CurrentApplicationId] bigint NULL
, CONSTRAINT [sqlite_master_PK_Customers] PRIMARY KEY ([Id])
, FOREIGN KEY ([CurrentApplicationId]) REFERENCES [Applications] ([Id]) ON DELETE RESTRICT ON UPDATE NO ACTION
);
CREATE UNIQUE INDEX [IX_Customers_CurrentApplicationId] ON [Customers] ([CurrentApplicationId] ASC);
CREATE TABLE [Applications] (
[Id] INTEGER NOT NULL
, [CustomerId] bigint NULL
, CONSTRAINT [sqlite_master_PK_Applications] PRIMARY KEY ([Id])
, FOREIGN KEY ([CustomerId]) REFERENCES [Customers] ([Id]) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE INDEX [IX_Applications_CustomerId] ON [Applications] ([CustomerId] ASC);
Exactly what we wanted.
Now, how you query the active and inactive applications in this configuration? Something like this:
var customerId = 1;
using (var ctx = new DataContext())
{
var currentApplication = (
from customer in ctx.Customers
where customer.Id == customerId
select customer.CurrentApplication
).FirstOrDefault();
var pastApplications =
(
from customer in ctx.Customers
from application in customer.Applications
where customer.Id == customerId && customer.CurrentApplication != application
select application
).ToArray();
}
I suggest you to read through the acticles to be found here to get familiar with EF Core.
As for relational DB modelling this site seems a useful resource.
Using EFCore, the following would work:
public class Customer
{
[Key]
public int ID {get; set;}
//other properties
//Navigation Property
public virtual ICollection<Application> Applications{ get; set; }
}
public class Application
{
[Key]
public int ID {get; set;}
[ForeignKey("Customer")]
public int CustomerID{get; set;}
public DateTime ApplicationDate{get; set}
//other properties
public bool IsCurrent { get; set; }
}
I am assuming your are using Code First, so this will be the correct way to do your mappings.
After migrating and updating the context, you could use some backend code to always ensure that your most recent application returns as IsCurrent.
You would can then select your current application as follows:
private yourContext _context;
var yourContext = _context.Customers
.Include(m=>m.Application)
.Where(m=> m.isCurrent==false)
.Single(a=>a.);
return yourContext;
You would of course have to set up your constructor with the context etc

Create Foreign Key to a Unique Key in another Entity with EF Core

I have a Program entity like this
public class Program : IEntityBase
{
public int Id { get; set; }
public string ProgramCode { get; set; }
public string Name { get; set; }
public int DegreeTypeID { get; set; }
public DegreeType DegreeType { get; set; }
}
with programCode created as a unique key with this implementation
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Program>().HasAlternateKey(d => d.ProgramCode).HasName("AK_ProgramCode");
}
I have another entity ApplicantProgram with this definition
public class ApplicantProgram : IEntityBase
{
public int Id { get; set; }
public int ApplicantID { get; set; }
public Applicant Applicant { get; set; }
[Required]
public string FirstChoiceID { get; set; }
[Required]
public string SecondChoiceID { get; set; }
[Required]
public string ThirdChoiceID { get; set; }
public string SessionID { get; set; }
}
Which has FirstChoiceID, SecondChoiceID & ThirdChoiceID having ProgramCode in the program table.
Now these are my questions,
How do i get Program.Name property from ApplicantProgram knowing the FirstChoiceID that is to link to Program.ProgramCode?
Is it possible to create a Navigation property to program from ApplicantProgram?
How do i create a foreign key from ApplicantProgram to Program based off the ChoiceIDs that should link to Program.ProgramCode without using Program.Id?
Thank you for pausing to read this.
(1) How do I get Program.Name property from ApplicantProgram knowing the FirstChoiceID that is to link to Program.ProgramCode?
There is nothing specific to EF here, you could use the typical data correlation operator - join. Just because you have 3 related properties, you would need 3 joins as well:
var query =
from applicantProgram in db.ApplicantPrograms
join firstChoice in db.Programs on applicantProgram.FirstChoiceID equals firstChoice.ProgramCode
join secondChoice in db.Programs on applicantProgram.SecondChoiceID equals secondChoice.ProgramCode
join thirdChoice in db.Programs on applicantProgram.ThirdChoiceID equals thirdChoice.ProgramCode
select new
{
ApplicantProgram = applicantProgram,
FirstChoice = firstChoice,
SecondChoice = secondChoice,
ThirdChoice = thirdChoice,
};
Inside the select, you could get the whole related objects as above, or specific properties like firstChoice.Name, secondChoice.Name etc.
But you won't need all that in EF once you define the navigation properties, which leads us to:
(2) Is it possible to create a Navigation property to program from ApplicantProgram?
(3) How do I create a foreign key from ApplicantProgram to Program based off the ChoiceIDs that should link to Program.ProgramCode without using Program.Id?
These two are interrelated. While it's possible to define a FK without navigation property, the navigation property would allow you simple access to related entity properties inside the LINQ queries as well as simple eager loading the related entity as part of the entity which is using it.
Start by adding the 3 navigation properties (one for each FK property) in ApplicantProgram class:
public Program FirstChoice { get; set; }
public Program SecondChoice { get; set; }
public Program ThirdChoice { get; set; }
and the following fluent configuration:
builder.Entity<ApplicantProgram>()
.HasOne(e => e.FirstChoice)
.WithMany()
.HasForeignKey(e => e.FirstChoiceID)
.HasPrincipalKey(e => e.ProgramCode)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicantProgram>()
.HasOne(e => e.SecondChoice)
.WithMany()
.HasForeignKey(e => e.SecondChoiceID)
.HasPrincipalKey(e => e.ProgramCode)
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicantProgram>()
.HasOne(e => e.ThirdChoice)
.WithMany()
.HasForeignKey(e => e.ThirdChoiceID)
.HasPrincipalKey(e => e.ProgramCode)
.OnDelete(DeleteBehavior.Restrict);
What we have here is the standard many-to-one relationship configuration - with HasOne(...) specifying the reference navigation property, WithMany() specifying no corresponding collection navigation property, HasForeighKey(...) specifying the corresponding FK property, and also the typical for multiple relationships to one and the same table turning off the cascade delete in order to avoid the multiple cascade paths problem.
What is specific thought (and is the EF Core improvement over EF6) is the HasPrincipalKey(...) method which allows you to specify other unique key property instead of the PK (by default) to be used by the FK relationship. Which in the combination with HasAlternateKey(...) on the other end allows to achieve the desired FK relationship setup.
And basically that's all. Now the query from (1) could be simply
var query =
from applicantProgram in db.ApplicantPrograms
select new
{
applicantProgram,
firstChoice = applicantProgram.FirstChoice,
secondChoice = applicantProgram.SecondChoice,
thirdChoice = applicantProgram.ThirdChoice,
};
Similar to (1), you could project the whole related objects or just properties you need.
Or you could get the ApplicantProgram instances with populated related Program properties by adding Include operators to the ApplicantProgram query (the so called eager loading):
var query = db.ApplicantPrograms
.Include(applicantProgram => applicantProgram.FirstChoice)
.Include(applicantProgram => applicantProgram.SecondChoice)
.Include(applicantProgram => applicantProgram.ThirdChoice);

Categories