开发者

EF4 Code-First: To Include or to not Include the Foreign Keys in the model when setting up an Association

In some of the Code-First EF4 walk-throughs, you see a pattern like开发者_Python百科 this when defining POCOs:

public class Product
{
    public int ID { get; set; }

    public int ManufacturerId { get; set; }
    public virtual Manufacturer Manufacturer { get; set; }
}

Why should Product have both a ManufacturerId and a reference to Manufacturer? Is it something to do with lazy-loading?


It really comes back to the story of Entity Framework: In EF1 we had only Independent Association meaning that FKs (e.g. ManufacturerId) were not exposed on the dependent object (e.g. Product) and you only work with the navigation property (e.g. Manufacturer). In EF4 a new type of association introduced: Foreign Key Association where FKs surfaced in the model and you can directly work with them.

So, the below is still a perfectly valid model but it's kind of EF1 style (i.e. Independent Association):

public class Product {
    public int ID { get; set; }
    public virtual Manufacturer Manufacturer { get; set; }
}

That said, it is recommended to always include foreign keys in the objects since it gives you ultimate flexibility to work with your object model:

public class Product {
    public int ID { get; set; }
    public int ManufacturerId { get; set; }
    public virtual Manufacturer Manufacturer { get; set; }
}

The interesting point is that by convention, EF code first will recognize ManufacturerId as to be the FK for Manufacturer navigation property and will create a relationship based on that in the database.

BTW, it doesn't have anything to do with lazy loading, lazy loading will work with or without the FKs as long as you mark you navigation property as vitual like you did in your model.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜