DEV Community

Discussion on: Tried Entity Framework Core 5.0's Many-to-Many support

Collapse
 
shibayan profile image
Tatsuro Shibamura

There's no need to think too hard. You can use the same methods as you normally use with collections.

class Program
{
    static async Task Main(string[] args)
    {
        using var context = new AppDbContext();

        var entry = new Entry
        {
            Title = "buchizo"
        };

        // Get exists tag
        var existsTag = await context.Tags.FirstAsync(x => x.Name == "kosmosebi");

        entry.Tags.Add(existsTag);

        await context.AddAsync(entry);
        await context.SaveChangesAsync();

        var existsEntry = await context.Entries
                                       .Include(x => x.Tags)
                                       .FirstAsync(x => x.Id == 1);

        // Remove first tag
        existsEntry.Tags.RemoveAt(0);

        await context.SaveChangesAsync();
    }
}