Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Linq for Foreign Key

I am trying to create a table that shows all users based on the selected program.

Programs: Id (key), program(string)
ProgramUsers: Id(key), username, program(foreign key), programaccess

Client input: program(string)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var programUsers = context.ProgramUsers
                     .Include("Program")
                     .Where(b=>b.Program == clientInput.Program)
                     .ToList();

Of course, since b.Program is an int and clientInput.Program is string this does not work. Can someone please help me?

>Solution :

  1. The ProgramUsers class needs a ProgramId property and a Program reference property.

  2. The Program needs a ProgramUsers collection navigation property.

using System.ComponentModel.DataAnnotations.Schema;

public class ProgramUsers
{
    public int Id { get; set; }
    public string Username { get; set; }

    [ForeignKey("Program")]
    public int ProgramId { get; set; }

    public Program Program { get; set; }
}

public class Program
{
    public int Id { get; set; }

    [Column("Program")]
    public string ProgramName { get; set; }

    public ICollection<ProgramUser> ProgramUsers { get; set; }
}

To configure in Fluent API if you are using Entity Framework Core:

modelBuilder.Entity<ProgramUser>()
            .HasRequired<Program>(x => x.Program)
            .WithMany(g => g.ProgramUsers)
            .HasForeignKey<int>(x => x.ProgramId); 

And to get the related entity for ProgramUsers in your query, assume that you are trying to get the program users by program name:

var programUsers = context.ProgramUsers
                     .Include(x => x.Program)
                     .Where(b => b.Program.ProgramName == clientInput.Program)
                     .ToList();

Reference: Data Annotations – ForeignKey Attribute in EF 6 & EF Core

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading