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

Time:12-22

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);

CodePudding user response:

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);
    }
  • Related