How to Add an Unidirectional One to Many Relationships in EF 6.4.4?

0

Issue

I have 2 classes:

public class Client
{
    public int Id { get; set; }
}
public class ClientRequest
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
}

I cannot modify Client class in any way (it’s external); I want to configure unidirectional one to many relationships between those 2 models. So Client 1 ← * ClientRequest and I can only navigate from ClientRequest to Client. How can I do this?

In EFCore I would do:

entity.HasOne(e => e.Client)
      .WithMany()
      .HasForeignKey(e => e.ClientId)
      .OnDelete(DeleteBehavior.ClientSetNull);

but I don’t have those methods in EF 6.4.4.

Would it be as simple as:

modelBuilder?.Entity<ClientRequest>()
                     .HasRequired(e => e.Client);

Solution

In EF 6.4.4 configure the relationship like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ClientRequest>()
            .HasRequired(x => x.Client)
            .WithMany()
            .HasForeignKey(x => x.ClientId)
            .WillCascadeOnDelete(false);

            
        base.OnModelCreating(modelBuilder);
    }

Answered By – David Browne – Microsoft

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More