Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

ef code first - Why does EF5 create foreign keys with _Id, but recommend naming convention Id without the underscore?

I have columns in my database that EF put in for me, that are classname followed by _Id. However much of the documentation recommends that the naming convention for foreign keys is the classname followed by Id without the underscore.

Like this post I dont want to have both conventions in my database.

Code First creates a foreign key in the database using the pattern [Name of navigation property]_[Primary Key of related class]

Why the 2 apparently inconsistent conventions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Every entity that holds a reference to another entity should have a property named ForeignEntityId (note the lower case d in Id).

If you set up your entities following the exact pattern of this example, all your columns should be named according to convention:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Order> Orders { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; } // this property is important
    public string ProductName { get; set; }
    public decimal Price { get; set; }

    public virtual Customer Customer { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...