Search code examples
c#entity-frameworknavigation-properties

Implement a navigation property in c# class


i have 2 entities each with a relating c# class. I set up a navigation property on table A to contain a reference to many items in table B. When i make a new table A class object i need to be able to create the collection of table B objects in table A. How do i set up the navigation property in the table A c# class?

DATAMODEL: http://bluewolftech.com/mike/mike/datamodel.jpg


Solution

  • Navigation properties are simple in EF. The example below shows how a navigation property would look:

    public class Foo
    {
        public int FooId { get; set; }
        public string SomeProperty { get; set; }
    
        public virtual IEnumerable<Bar> Bars { get; set; }
    }
    

    Where Foo represents tableA and Bar represents tableB. They key word for the navigation property is virtual which enables lazy-loading by default. This is assuming you're using EF4.1 Code First.

    EDIT

    Off the top of my head, this should be a good starting template for you:

    public class PointOfInterestContext : DbContext
    {
        public IDbSet<PointOfInterest> PointOfInterest { get; set; }
        public IDbSet<POITag> POITag { get; set; }
        public IDbSet<Tag> Tag { get; set; }
    
        public override OnModelCreating(DbModelBuilder modelBuilder)
        {
            // custom mappings go here
            base.OnModelCreating(modelBuilder)
        }
    }
    
    public class PointOfInterest
    {
        // properties
        public int Id { get; set; }
        public string Title { get; set; }
        // etc...
    
        // navigation properties
        public virtual IEnumerable<POITag> POITags { get; set; }    
    }
    
    public class POITag
    {
        // properties
        public int Id { get; set;}
        public int PointOfInterestId { get; set; }
        public int TagId { get; set; }
    
        // navigation properties
        public virtual PointOfInterest PointOfInterest { get; set; }
        public virtual Tag Tag { get; set; }
    }
    
    public class Tag
    {
        // properties
        public int Id { get; set; }
        public string TagName { get; set; }
        // etc...
    
        // navigation properties
        public virtual IEnumerable<POITags> POITags { get; set; }    
    }
    

    Then you would implement the other logic in your business objects. The entities are supposed to be lightweight and at most should have data attributes. I prefer to use the fluent mappings through the OnModelCreating though.

    Here are a few good references:
    MSDN - EF 4.1 Code First
    Code First Tutorial