When looking at questions and answers on this site and reading some of the top Google-ranked tutorials on Code First development I frequently see the following pattern...
public class Category
{
public Category()
{
Products = new Collection<Product>();
}
public Guid ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public Guid ID { get; set; }
public string Name { get; set; }
public DateTime DateAdded { get; set; }
public Guid CategoryID { get; set; } // Seemingly redundant property
public virtual Category Category { get; set; }
}
When searching for Code First tutorials the following two pages come up that use this same pattern:
http://www.codeproject.com/Articles/327945/Architecture-Guide-ASP-NET-MVC3-Entity-Framework-C
Question: So what is the point of having the foreign key property on the Code First C# object? In the above example you can omit CategoryID
from the Product
class and everything will work just fine. The foreign key Category_ID
will still be created in the database.
The only thing I could think of is that people might like to be able to specify whether the relationship is optional using nullable types instead of the fluent API, but I think it really confuses things to have both a Category
and CategoryID
property.
So before I go around and remove all my foreign key properties, is there anything that I'm missing here? What's the point of doing this?
Thanks!