开发者

Why does Entity Framework make certain fields EnityKeys when they are not even PK's in the source DB?

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 al开发者_JAVA百科l the fields where it was added.

Thanks for your advice!


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜