© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
7 replies
TotechsStrypper

❔ EFCORE DESIGN ONE TO MANY

Can you guys help me to design a correct one to many relationships in this case

The problem

I have this LINQ below
public async Task<Conversation?> FindByNameAsync(string name, CancellationToken cancellationToken = default)
        => await _dbSet.Include(conversation => conversation!.ChatMessages)
                            .ThenInclude(chatMessage => chatMessage.User)
                        .Take(10).FirstOrDefaultAsync(x => x.Name == name!, cancellationToken);
public async Task<Conversation?> FindByNameAsync(string name, CancellationToken cancellationToken = default)
        => await _dbSet.Include(conversation => conversation!.ChatMessages)
                            .ThenInclude(chatMessage => chatMessage.User)
                        .Take(10).FirstOrDefaultAsync(x => x.Name == name!, cancellationToken);


This one will be cycle because it's include the User and the User have ChatMessages like in the image so this will cause recursive cycle when loading the data

My solution (but fail)

On
User.cs
User.cs
I could remove the below properties
public virtual ICollection<ChatMessage> ChatMessages { get; set; } = new HashSet<ChatMessage>();
public virtual ICollection<ChatMessage> ChatMessages { get; set; } = new HashSet<ChatMessage>();


But I end up need it for setup Delete Cascade behavior
        builder.Entity<ChatMessage>(entity =>
        {
            entity.HasOne(i => i.User).WithMany(s => s!.ChatMessages).OnDelete(DeleteBehavior.Cascade);
        });
        builder.Entity<ChatMessage>(entity =>
        {
            entity.HasOne(i => i.User).WithMany(s => s!.ChatMessages).OnDelete(DeleteBehavior.Cascade);
        });

Any suggestion ?
image.png
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ EFCore One-To-One
C#CC# / help
3y ago
❔ Can't seed one-to-many relation efcore
C#CC# / help
3y ago
Help setting up Many to Many in EFCore
C#CC# / help
4y ago
❔ EFCore: One has mutliple Entities
C#CC# / help
3y ago