0

I am working on a simple database and to be specific here is the model generated by database first approach (Visual Studio 2017 Community, Entity Framework 6.2): Generated Database Model

I'd like the UserMessage table to be able to point to itself with a field named AnswerId, this is a nullable foreign key referencing its primary key. Again, to be specific, here is the part where I create the table: UserMessage table script

My problem is that when Entity Framework generates the classes based on the existing database everything goes fine except for this particular table, in which EF suggests (I don't know why) that the UserMessage table has a multiplicity of 0..1 - * to itself while it should 1 - 0..1 (because a message may have a direct answer, but not more than 1, though that message, which is the answer, could also have an answer, so it's just like a linked list). Here is the generated class: UserMessage generated class

To sum up the whole thing: I'd like to know why Entity Framework generates my class the way it does, and how could I make it generate it so that I only have a virtual property pointing to the answer (in case it has one), but not a collection.

Thank you for your answers!

George
  • 5
  • 3

2 Answers2

1

I think what you're seeing is a correct interpretation by EntityFramework. UserMessage1 represents a collection of all the UserMessages that have references to the parent as their answer. I understand that you probably won't use that collection for anything but it's not wrong that it's there. UserMessage2 seems to be the property you're looking for. Maybe you could rename those properties in the diagram so they're not confusing.

UserMessages1 = MessagesThatReferenceMe

UserMessages2 = the Message that I may or may not reference

I don't see how you can stop EF from generating this collection. I think if you delete the property in the diagram you will have to delete it every time you update the diagram.

  • Oh I see now, I absolutely didn't understand why UserMessages1 even existed, but as I read your comment I tried make some references and it turned out that since this foreign key is not unique, multiple messages could mark a single one as their answer. I will figure something out since making it unique would restrain having more than one null value, but thank you for your answer! – George Mar 01 '18 at 23:06
0

Maybe try deleting the 2nd UserMessage navigation property in your model.

tbean
  • 7
  • 2
  • I figured that if I modified it a bit, then it could be useful. Thank your for your answer! – George Mar 01 '18 at 23:07