简体   繁体   English

使用实体框架联接3个表

[英]Join 3 tables using Entity Framework

How can I build a model using Entity Framework to join 3 tables? 如何使用Entity Framework建立模型以联接3个表?

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? 是否有更好的方法使用Entity Framework在3个表之间建立关系?

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. 谢谢。

I'm assuming that you're using Code-First Entity Framework here, and that you have your KeywordAdCategory object in your database as well. 我假设你在这里使用代码优先实体框架,和你有你的KeywordAdCategory对象在数据库中也是如此。 In which case, just simply do the following in your KeywordAdCategory class to do the proper mapping: 在这种情况下,只是简单的做下你KeywordAdCategory课上做适当的映射:

[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. 这样做应该做的正确的映射,把FKS您KeywordAdCategory表中,从而让您拥有良好的导航性能,其他对象的能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM