简体   繁体   中英

Entity Framework (code first) - Relation one to many

I have trouble with setting a one to many relationship in EF (.net Core) 6.

I have a table with users

public class UserDomain{
   Id{get;set;}
   Name{get;set;}
}

I have a table with messages where I want to track who has seen the messages

public class MessageDomain{
  Id{get;set;}
  Title{get;set;}
  Message{get;set;}
  List<UserDomain> UsersRead{get;set;}
}

Now when I add a migration it sets a column on the user table with an integer of the id of the message. But that is not what I want. Because then the read message switches every time I set a message as read.

I tried

modelBuilder.Entity<MessageDomain>().HasMany(x => x.UsersRead).WithOne().HasForeignKey(x => x.Id);

But that also did not work.

In order to have one-to-many relationship you will have to have that column which will be a FK to the other table.

In your case if MessageDomain needs to have relation ship to many users. You need to add MessageDomainId column in UserDomain class. - it will also generate that column in the db.

But that is not what I want. Because then the read message switches every time I set a message as read.

You will have to update the reference on UserDomain each time that happens

Based on the comment on the answer above you will probably need to create an additional table.

  1. UserDomain
  2. UserMessages
  3. MessagesDomain

Where user will have a one to many relationships with UserMessages and then MessagesDomain will then have One to many relationship with UserMessages.

public class UserDomain
{
   Id{get;set;}
   Name{get;set;}
   List<UserMessages> ReadMessages{get;set;}
}

public class UserMessages
{
   UserId{get;set;}
   MessageId{get;set;}
   MessageDomain MsgDomain{get;set;}
   UserDomain UserDomain{get;set;}
}

public class MessageDomain{
  Id{get;set;}
  Title{get;set;}
  Message{get;set;}
  List<UserMessages> ReadBy{get;set;}
}

You will then use UserMessages to track which user read which message, you can then include the related tables in your query to get all the data.

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