简体   繁体   中英

Code First Entity Framework C#, Many to Many Mapping, Junction Table Created but list property not populated on object

Many Users can Send Many Message Requests to Many Other Users

USERS

Id

Name

Age

MESSAGE REQUESTS

Id

Message

FromUserID

ToUserID

ICollection<User> RequestUsers

I am trying to set up my class for this using code first. I have managed to get code first and EF to create the junction table but this is no good as the MessageRequest junction table is only used by the database. I am looking for a way to add it to part of the context so I can work with it in code.

I want to be able to get a list of all users that have had a message request sent to them based on the Message Request ID.

Even though code first created the junction table, when I debug the application and inspect RequestUsers property it is null and I want it to be populated automatically to work with in code.

I have tried all kinds of mappings but can't get it to work.

Can someone please explain how to layout the two classes for code first in ER and how I can get the RequestUsers Property to be populated automatically with the list of related users?

Any time you're talking about EF classes, you should post the class definitions. It's nearly impossible to answer a question like this otherwise. That said, I can take a guess that you neglected to add the virtual keyword to your collection, ie:

public virtual ICollection<User> RequestUsers { get; set; }

Without virtual EF will not load the relationship.

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