我有多对多关系,但 EF Core 似乎不识别它。
JobOffer
和JobOfferTag
之间存在关系。 JobOffer
继承自BaseJobOffer
:
public class BaseJobOffer
{
[Required]
[TrimmedStringLength(50, 20)]
public required string Title { get; set; }
[Required]
[TrimmedStringLength(500, 100)]
public required string Description { get; set; }
[Required]
[Range(5, int.MaxValue)]
public required int PaymentInDollars { get; set; }
[Required]
public required PaymentMethod PaymentMethod { get; set; }
public BaseJobOffer()
{
}
[SetsRequiredMembers]
public BaseJobOffer(BaseJobOffer offer)
{
Title = offer.Title;
Description = offer.Description;
PaymentInDollars = offer.PaymentInDollars;
PaymentMethod = offer.PaymentMethod;
}
}
JobOffer.cs
public class JobOffer : BaseJobOffer
{
public int Id { get; set; }
public DateTimeOffset Created { get; private set; } = DateTimeOffset.UtcNow;
public ICollection<JobOfferTag> Tags = []; // Reference navigation for many to many relationship
public long UserId { get; set; }
public ApplicationUser User { get; set; } = null!;
public JobOffer() : base()
{
}
[SetsRequiredMembers]
public JobOffer(BaseJobOffer offer) : base(offer)
{
}
}
JobOfferTag.cs
public class JobOfferTag
{
public int Id { get; set; }
public required string Value { get; set; }
// Reference navigation for many to many relationship
public ICollection<JobOffer> JobOffers { get; set; } = [];
}
EF Core 仅创建
joboffers
和 joboffertag
表,其中 joboffers
具有 JobOfferTagId
列,而根本不应该出现这种情况。我希望 EF Core 创建一个连接表。
我认为为了自动发现多多关系,你需要这样做:
public class JobOffer : BaseJobOffer
{
public int Id { get; set; }
public DateTimeOffset Created { get; private set; } = DateTimeOffset.UtcNow;
public ICollection<JobOfferTag> JobOfferTags { get; set; }
public long UserId { get; set; }
public ApplicationUser User { get; set; } = null!;
}
并且:
public class JobOfferTag
{
public int Id { get; set; }
public required string Value { get; set; }
public ICollection<JobOffer> JobOffers { get; set; }
}
另请参阅所有 EF-Core-约定