Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

Relationship Using Code first with Existing database

When defining a relationship between two types is it important to include a navigation property on both types, such as in the following example:

    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public Category Category { get; set; }
    }

    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public ICollection<Product> Products { get; set; }
    }

Can I do without including the navigation property in Category ?

Upvotes: 0

Views: 84

Answers (1)

Richard Forrest
Richard Forrest

Reputation: 3615

If you just want it infered by code first convention then yes you need both on either side. I'd also make the collection "virtual" to support lazy loading.

You can set it up using the fluent configuration when the model is built. It would be something like this

modelBuilder.Entity<Product>()
    .HasMany(x => x.Category) 

Upvotes: 1

Related Questions