I have seen that Tables which do not have primary keys do not appear in the wizard of LINQ and cannot be dragged to dbml file. Has anyone faced the same behavior? Can anyone explain the reason why tables require primary key to access through LINQ?
Asked
Active
Viewed 268 times
1 Answers
1
Entity Framework needs a primary key (or some sort of key) in order to work properly. This is because any entity pulled down by a data context needs to have a way to differentiate (and match) itself from other entities. Take this example:
// Two different variables, but should pull the same entity.
var entity1 = context.Entities.First();
var entity2 = context.Entities.First();
entity2.PropertyA == "OldValue" // Evaluates to true.
entity1.PropertyA = "NewValue";
context.SaveChanges();
// entity2 is updated despite not having its property directly modified
// by this code.
entity2.PropertyA == "NewValue" // Evaluates to true.
These entities are kept synced up to each other via an Entity Key that is known to be unique in the db via the primary key. You can still map this manually and tell EF what identifies each entity, but it can't figure it out automatically. See this answer for some more information on the "why can't I do it via the wizard" part of your question.