0

I have a problem with the table creation of EF5 Code first. I'm going to demonstrate two cases and their outputs. What I want to know what the difference between them and how I could be successful on my goal.

Case 1

public class User{

public int ID { get; set; }

public string Name { get; set; }

public ICollection<UserMessage> Messages { get; set; }

}

public class UserMessage{

public int ID { get; set; }

public string Message { get; set; }   

public User CreatedBy { get; set; }

public ICollection<User> PermittedUsers {get; set;}

}

Now in this case, entity framework generates only User and UserMessage classes that are only binding to each other with UserMessage_ID in User and CreatedBy_ID in UserMessage.

The problem that I'm curious is in here. How will EF5 recognize permitted users whenever I create a new message? Is it going to duplicate the same message for each permitted users? Or what?

Case 2

public class User{

public int ID { get; set; }

public string Name { get; set; }

public ICollection<UserMessage> Messages { get; set; }

}

public class UserMessage{

public int ID { get; set; }

public string Message { get; set; }   

public ICollection<User> PermittedUsers {get; set;}

}

In this case I have removed just only CreatedBy in UserMessage entity. Now EF5 generates 3 tables named : User, UserMessage, UserMessageUsers. The links between UserMessage and User is now over UserMessageUsers so that we can easily manage permitted users.

How can I add CreatedBy property into UserMessage without breaking up Case 2 ?

kkocabiyik
  • 4,246
  • 7
  • 30
  • 40
  • 2
    http://stackoverflow.com/questions/8228948/entity-framework-using-both-many-to-many-and-one-to-many-to-same-entity this is exactly the answer – kkocabiyik Nov 11 '12 at 17:10

1 Answers1

0

You can use fluent api to configurate it:

modelBuilder.Entity<UserMessage>()
    .HasMany(d=>d.PermittedUsers)
    .WithMany(d=>d.Messages)
    .Map(c=>c.ToTable("UserMessageUsers"));
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38