我有以下2个课程:
public class AdvertiserConcern
{
public int Id { get; set; }
public required int ConcernId { get;set; }
public required int AdvertiserId { get;set; }
public Client? Concern { get; set; }
public Client? Advertiser { get; set; }
}
public class Client
{
public int Id { get; set; }
public ICollection<AdvertiserConcern>? AdvertiserConcernsAdvertisers { get; set; }
public ICollection<AdvertiserConcern>? AdvertiserConcernsConcerns { get; set; }
}
我正在努力处理客户与广告商关注点的关系。我一开始只从“广告商”开始,但也没能成功。我在 AdvertiserConcern 上的 Advertiser 导航属性上添加 [ForeignKey("AdvertiserId")] ,并在 Client.AdvertiserConcernsAdvertisers 上添加 [InverseProperty("Advertiser")] ,在创建迁移时,它实际上想要在 AdvertiserConcern 上添加一列 ClientID ,该列已经是那里有 AdvertiserId。
我也许可以用 FluentAPI 来实现它,但在模型上要清楚。我做错了什么?
在大多数情况下,
EF
可以根据约定识别关系,但是当一个表中的两个或多个外键存在于另一表中时,您应该使用OnModelCreating
在FLUENT API
方法中显式配置关系,如下所示:
modelBuilder.Entity<AdvertiserConcern>(entity =>
{
entity.HasOne(s => s.Advertiser)
.WithMany(d => d.AdvertiserConcernsAdvertisers)
.HasForeignKey(d => d.AdvertiserId);
entity.HasOne(s => s.Concern)
.WithMany(d => d.AdvertiserConcernsConcerns)
.HasForeignKey(d => d.ConcernId);
});