如果您有一个 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; }
}
回答1
这不再是 EF 可以为您隐式处理的两个实体之间的多对多关系,而是三个实体之间的两个一对多关系。
创建具有两个 FK(Ad
、ServiceType
)和价格字段的中介 AdServiceType
(或任何其他适当的名称)。 AdServiceType
然后充当您的广告和服务类型之间的连接关系。
回答2
基于 https://stackoverflow.com/users/952296/flater 答案,您应该创建一个中间类:
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; }
}