Share via

Help with relationships without using Id...

Guillermo Perez 26 Reputation points
2021-08-10T04:37:06.047+00:00

Please help on how to form a relationship correctly. I have 2 tables with many fields, one contains users, the other a list of messages. Both are not related by the user Id nor the messages Id, instead these are formed like this: (example only)

User {
Id
...
MessagesId (string by the way)
...
}

Messages{
id
...
MessageGroupId (String)
}

I would like to be able to create a relationship between these 2, that the user can get the list of messages from the other table using the MessagesId and viceversa, that the table Messages could get the user the message belongs to by using its MessageGroupId...

I have tried but received a bunch of errors, maybe because in the list of users, a user could or not have the MessagesId (as not all users send or receive messages)

Any help will be appreciated, thank you in advance!

Developer technologies | .NET | Entity Framework Core
0 comments No comments

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,661 Reputation points
    2021-08-10T05:40:27.683+00:00

    Hi GuillermoPerez-9757,
    >>that the user can get the list of messages from the other table using the MessagesId and viceversa, that the table Messages could get the user the message belongs to by using its MessageGroupId...
    According to my understanding, you need to configure a one-to-many relationship (a user has multiple messages, and multiple messages correspond to one user).
    And you can configure a relationship via the Fluent API.
    Code looks like below:

    Class MyContext : DbContext  
    {  
        public DbSet<User> users { get; set; }  
        public DbSet<Messages> messages { get; set; }  
      
        protected override void OnModelCreating(ModelBuilder modelBuilder)  
        {  
            modelBuilder.Entity<Messages>()  
                .HasOne(m => m.User)  
                .WithMany(u => u.messages);  
        }  
    }  
    public class User  
    {  
        public int Id { get; set; }  
        public string MessagesId { get; set; }  
        ...  
        public List<Messages> messages { get; set; }  
    }  
      
    public class Messages  
    {  
        public int id { get; set; }  
        public string MessageGroupId{ get; set; }  
        ...  
        public User User { get; set; }  
    }  
    

    More details you can refer to this document.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.