Carlos Blanco
Carlos Blanco

Reputation: 8772

Entity Framework. Code First. Relationship with a table in between

I have a Database similar to the one in this example. Not the Student-courses scenario, but 2 tables that have a common third related to both of them.

My case is, Items, PerformanceGraphItems and PerformanceGraphSeries.

Each item can have several GraphItems and a GraphItem belongs to a GraphSeries row. How could I model it in the Entity Framework in order to be able to access the GraphSeries that belong to an Item?

Something like this.

public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }


        public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }
    }



public class PerformanceGraphItem
    {
        [Key]
        public int Id { get; set; }
        [ForeignKey("Item")]
        public int ItemId { get; set; }
        public int SeriesId { get; set; }
        public short Year { get; set; }
        public double RateOfReturn { get; set; }
        public virtual Item Item { get; set; }
        [ForeignKey("SeriesId")]
        public virtual PerformanceGraphSeries PerformanceGraphSeries { get; set; }

    }


public class PerformanceGraphSeries
    {
        public int id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<PerformanceGraphItem> PerformanceGraphItems { get; set; }

    }

Upvotes: 1

Views: 833

Answers (1)

Tim
Tim

Reputation: 15247

It seems to me that what you have is pretty close to what you want, though I would change your

public virtual ICollection<PerformanceGraphSeries> PerformanceGraphSeries { get; set; }

line to instead be

public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries);
    }
}

or

public virtual IEnumerable<PerformanceGraphSeries> PerformanceGraphSeries
{
    get
    {
        return PerformanceGraphItems.Select(pgi => pgi.PerformanceGraphSeries)
                                    .Distinct();
    }
}

depending on your scenario.

Thius is because you're not really modeling a database that has a direct connect between Item and PerformanceGraphSeries - so you don't want your database to be generated that way. But this still allows you to access it in one property (instead of having to do that query everywhere).

Also, since you're using virtual in most places, I assume you're trying to go for proxy objects - make sure you're setting all of your properties to be virtual, otherwise it won't happen.

Upvotes: 2

Related Questions