简体   繁体   中英

one to many relationship in Entity Framework on the same table

I have two tables, in which one user can have several contacts:

User(UserId, UserName)
Contact(UserId, ContactId)

Suppose I would like to get all the ContactNames from the UserNames in the User Table by the Userid.

Note that the Contact table cannot be seen in the current data context, it has been turned into a many to many relationship

How can I do the query?

What If I need to insert or delete?

I tried the "include" method but it does not work. Do you have any suggestions?

Thank you very much.

var id = 1; // id to find
context.Users
     .Where(x=>x.UserId = id)
     .SelectMany(x=>x.Users)
     .Select(x=>x.UserName)
     .ToArray();

替代文字

After generation from db your model has 2 sub-collections: Users and Users1.

  1. One of it corresponds to users, that are contacts for current user.
  2. Another stores users, that current user is contact for.

You can rename them to represent their meaning to Contacts and ContactsFor via editor.

替代文字

If you still want to have 2 types instead of Type+(Many-To-Many Ref), then in editor you can delete reference, create new entity Contact, setup all mapping, add references. After all this is done - you will have model look like this: 替代文字

To Achieve this:

  1. Delete Many-To-Many reference
  2. Crete new Entity Contact
  3. Add properties ContactId and UserId, set StoreGeneratedPattern to none
  4. Add mappings for Contact
  5. Add associations for Contacts and ContactFor

But it's not that easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM