1

Starting out on an Entity Framework project.

Imported the Db I am going to use and right away noticed that many table fields were made into EntityKey types and the source fields are not even Keys. Doesn't seem to be a pattern as to which fields were made EntityKeys and which were not.

Is this normal? There were no options for this in the wizard. I don;t want to have to go through and remove this property for all the fields where it was added.

Thanks for your advice!

skaffman
  • 398,947
  • 96
  • 818
  • 769
user259286
  • 977
  • 3
  • 18
  • 38

2 Answers2

1

Each entity on your model requires a unique key, so EF can track and retrieve/persist these entities based on their unique identifier.

If your tables in your database don't have primary keys, then your database is not relational and therefore should not be used by an ORM like EF which is predominantly designed for RDBMS.

If you had an entity like this:

public class Orders
{
   public string Name { get; set; }
   public double Price { get; set; }
}

How would you retrieve a single order? How would you save a single order?

Crucial LINQ methods such as SingleOrDefault() would be useless, as there is no guarantee that this won't throw an exception:

var singleOrder = ctx.Orders.SingleOrDefault(x => x.Name == "Foo");

Whilst if you had an EntityKey and PK called "OrderId", this is guaranteed to not throw an exception:

var singleOrder = ctx.Orders.SingleOrDefault(x => x.OrderId == 1);
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Yes I get that, and my source DB DOES have PK's. My concern is that EF is making many other fields EntityKeys which in the source DB are NOT PK's. If your point is that EF needs to make EnitityKeys to be able to perform certain actions in LINQ, then why not make ALL the fields as EnitityKeys and not just some as has happened? – user259286 Jan 22 '11 at 13:39
  • Can you edit your question and show the table definition from SQL and the entity on the EDMX which EF has made the entity key? (e.g the particular issue you are having) – RPM1984 Jan 22 '11 at 22:22
0

http://msdn.microsoft.com/en-us/library/dd283139.aspx

I think as soon as you read the first paragraph you will understand the role of entity keys in Entity Framework.

George Taskos
  • 8,324
  • 18
  • 82
  • 147