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



如果你有一个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可以隐式处理的两个实体之间的多对多关系,而是三个实体之间的两个一对多关系。

创建一个中间的AdServiceType(或任何其他适当的名称),它有两个fk (Ad,ServiceType)和price字段。然后,AdServiceType充当广告和服务类型之间的连接关系。

基于@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; }
}

最新更新