I have a JobOffer
class which has a many-to-many relationship with the JobOfferTags
class.
I am getting the tags as a collection of strings from the client and then creating a collection with their database counterparts.
Collection<JobOfferTag> tags = [];
for (int i = 0; i < offer.Tags.Count; i++)
{
// Check if tag exists in db
string tag = offer.Tags.ElementAt(0);
JobOfferTag? dbTag = await dbContext.JobOfferTags.FirstOrDefaultAsync(t => t.Value == tag);
if (dbTag == null)
{
// ...
}
tags.Add(dbTag);
}
public class JobOffer : BaseJobOffer
{
public int Id { get; set; }
public DateTimeOffset Created { get; private set; } = DateTimeOffset.UtcNow;
public new ICollection<JobOfferTag> Tags = [];
public JobOffer() : base()
{
}
[SetsRequiredMembers]
public JobOffer(BaseJobOffer offer) : base(offer)
{
}
}
Although when I try setting the Tags
property to tags
, only the first item of tags
gets saved when calling DbContext.SaveChangesAsync()
.
JobOffer newOffer = new(offer)
{
Tags = tags,
UserId = user.Id
};
dbContext.JobOffers.Add(newOffer);
await dbContext.SaveChangesAsync();
EF Core only creates a row in the join table for the first tag.