Patrick
Patrick

Reputation: 2781

Join 3 tables using Entity Framework

How can I build a model using Entity Framework to join 3 tables?

At the moment I have:

public class KeywordAdCategory
{
    [Key]
    [Column("Keyword_Id", Order = 0)]
    public int Keyword_Id { get; set; }

    [Key]
    [Column("Ad_Id", Order = 1)]
    public int Ad_Id { get; set; }

    [Key]
    [Column("Category_Id", Order = 2)]
    public int Category_Id { get; set; }
}

But I don't have any navigation properties.

Is there a better way to build a relashionship between 3 tables using Entity Framework?

Also the Keyword, Ad and Category models:

public class Keyword
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Ad
{
    // Primary properties
    [Key]
    public int Id { get; set; }

    // Navigation properties
    public AdOperation AdOperation { get; set; }
    public Member Member { get; set; }
    public Address Address { get; set; }
    public Category Category { get; set; }

    public virtual ICollection<Picture> Pictures { get; set; }

    private ICollection<Feature> _features;
    public virtual ICollection<Feature> Features
    {
        get { return _features ?? (_features = new HashSet<Feature>()); }
        set { _features = value; }
    }
}

public class Category
{
    // Primary properties
    public int Id { get; set; }
    public int? CategoryParent_Id { get; set; }
    public int? CategoryGroup_Id { get; set; }
    public bool IsActive { get; set; }

    // Navigation properties
    public Keyword Keyword { get; set; }
}

Thanks.

Upvotes: 0

Views: 243

Answers (1)

Corey Adler
Corey Adler

Reputation: 16149

I'm assuming that you're using Code-First Entity Framework here, and that you have your KeywordAdCategory object in your database as well. In which case, just simply do the following in your KeywordAdCategory class to do the proper mapping:

[Key, ForeignKey("Keyword")]
[Column("Keyword_Id", Order = 0)]
public int Keyword_Id { get; set; }

[Key, ForeignKey("Ad")]
[Column("Ad_Id", Order = 1)]
public int Ad_Id { get; set; }

[Key, ForeignKey("Category")]
[Column("Category_Id", Order = 2)]
public int Category_Id { get; set; }

public virtual Keyword Keyword { get; set; }

public virtual Ad Ad { get; set; }

public virtual Category Category { get; set; }

Doing this should do the proper mappings, put FKs on your KeywordAdCategory table, and thus give you the ability to have good navigation properties to the other objects.

Upvotes: 1

Related Questions