There is such a model:

public class User { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<User> Collection1 { get; set; } = new List<User>(); public virtual ICollection<User> Collection2 { get; set; } = new List<User>(); } 

Further we fill our base a little:

 var context = new UsersContext(); var user1 = new User(); var user2 = new User(); var user3 = new User(); user1.Name = "user1"; user2.Name = "user2"; user3.Name = "user3"; user1.Collection1.Add(user2); user2.Collection1.Add(user3); context.Users.Add(user1); context.Users.Add(user2); context.Users.Add(user3); context.SaveChanges(); 

As you can see, no one in Collection2 is adding anyone.

Then I do this request:

 var user2 = context.Users.First(user => user.Name == "user2"); foreach (var u in user2.Collection2) Console.WriteLine($"{user2.Name} Collection2 {u.Name}"); 

And I get:

user2 Collection2 user1

Where does user2 appear in user2 in the second collection if I didn’t add anyone to it?

    1 answer 1

    You have Collection1 and Collection2 automatically defined as mutually inverse.

    Therefore, when user1 - (Collection1) - user2 appears in the context of the connection, feedback was added automatically.

    If collections are independent, not mutually inverse, adjust the connection between the navigation properties by overriding OnModelCreating or by arranging the correct InversePropertyAttribute

    • But how in this situation to use InversePropertyAttribute ? Well, in essence, I have two collections of the same essence. Could you write a small example? - Lightness
    • @Lightness just as usual. Specify the reverse navigation property, if any. - Pavel Mayorov
    • And if there is no reverse navigation property as in my situation, what should I do? - Lightness
    • @Lightness create it or use an alternative method - KO - Pavel Mayorov
    • Create it will not work. If you override OnModelCreating what do you need to write there? Please write a small example, because I am not particularly familiar with EntityFramework and do not understand what you mean. - Lightness