DEV Community

loading...

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

Collapse
pantonis profile image
pantonis

How do you update related entities (in your example how do you create a new entry with existing tags and delete existing tags from an existing entry)

Collapse
shibayan profile image
Tatsuro Shibamura Author

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();
    }
}