Home > front end >  EF Core/C#: Set many-to-many relationship with a variable field?
EF Core/C#: Set many-to-many relationship with a variable field?

Time:05-14

If you have an EF/asp.net Core app that has ads with services with a price. Where each ad can have many services (out of a predefined set of choices, like haircut, nail polish, etc. ) and a price that is variable for each ad. How do you form the many to many relationship?

public class Ad {
 ...
 ...
// the list of serviceTypes to choose from to add to your Ad.
 public List<ServiceType> Services { get; set; )
}

public class ServiceType {
...
 public string ServiceName { get; set; }
 // I can't set price here since every ad has its own price (varying) for the given serviceType!
public List<Ad> Ad { set; get; }
} 
`

CodePudding user response:

This is no longer a many to many relationship between two entities that EF can implicitly handle for you, but rather two one to many relationships between three entities.

Create an intermediary AdServiceType (or any other appropriate name) which has two FKs (Ad, ServiceType) and the price field. The AdServiceType then acts as the joined relationship between your ads and your service types.

CodePudding user response:

Based @Flater answer you should create an intermediate class:

public class Ad
{
    public long Id { get; set; }

    // the list of serviceTypes to choose from to add to your Ad.
    public ICollection<AdServiceType> AdServiceTypes { get; set; } = new HashSet<AdServiceType>();
}

public class ServiceType
{
    public long Id { get; set; }
    public string ServiceName { get; set; }
    
    // I can't set price here since every ad has its own price (varying) for the given serviceType!
    public ICollection<AdServiceType> AdServiceTypes { set; get; } = new HashSet<AdServiceType>();
}

public class AdServiceType
{
    public long AdId { set; get; }
    public long ServiceTypeId { set; get; }
    public Ad Ad { set; get; }
    public ServiceType Service { set; get; }
}
  • Related