EF Core/C#: 用变量字段设置多对多关系?

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

如果您有一个 EF/asp.net Core 应用程序,该应用程序包含带有价格服务的广告。每个广告可以有许多服务(在一组预定义的选择中,如理发、指甲油等)和每个广告的可变价格。如何形成多对多关系?

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

这不再是 EF 可以为您隐式处理的两个实体之间的多对多关系,而是三个实体之间的一对多关系。

创建一个具有两个 FK(AdServiceType)和价格字段的中介 AdServiceType(或任何其他适当的名称)。 AdServiceType 然后充当您的广告和服务类型之间的连接关系。

基于 @Flater 的答案你应该创建一个中间 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; }
}