EF4的间接导航字段

时间:2011-11-21 21:41:53

标签: c# linq entity-framework-4

我想知道是否可以在直接从数据库填充的类中拥有属性/字段。我知道直接实现这一点会破坏设计模式,例如关注点的分离,但我希望在OnModelCreating的{​​{1}}函数中进行一些配置。

在下面的示例中,给定DbContext,我想知道它出现在哪个Product

PriceTables

只是为了澄清:我的模型,如下所示,但它的工作方式相同(因此我需要这种类的分离,使用此"连接表&#34 ;)

AFAIK,使用LINQ我可以通过以下方式找到我想要的信息:

public class PriceTable
{
    public int ID { get; set; }
    public HashSet<Price> Prices { get; set; }

    public PriceTable()
    {
        Prices = new HashSet<Price>();
    }
}

public class Price
{
    public int ID { get; set; }        
    public double Value { get; set; }

    public int ProductID { get; set; }
    public virtual Product Product { get; set; }

    public int PriceTableID { get; set; }
    public virtual PriceTable PriceTable { get; set; }
}

public class Product
{
    public int ID { get; set; }
    public String Name { get; set; }

    // This is what I'd like to achieve
    /*
    public HashSet<PriceTable> PriceTables { 
        get {
            // and here, return something from the DB
        }
    }
    */
}

这意味着我想要嵌入我的 from p in Prices where p.Product.ID == MY_PRODUCT_ID select p.PriceTable 课程中的问题! 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我通过更改模型以匹配以下内容(将更改描述为注释)来完成我的目标:

public class PriceTable
{
    public int ID { get; set; }
    public HashSet<Price> Prices { get; set; }

    // New field, which allows me to query "all the Products in some PriceTable"
    public IEnumerable<Product> Products
        {
            get
            {
                return Prices.Select(p => p.Product);
            }
        }

    public PriceTable()
    {
        Prices = new HashSet<Price>();
    }
}

public class Price
{
    public int ID { get; set; }        
    public double Value { get; set; }

    public int ProductID { get; set; }
    public virtual Product Product { get; set; }

    public int PriceTableID { get; set; }
    public virtual PriceTable PriceTable { get; set; }
}

public class Product
{
    public int ID { get; set; }
    public String Name { get; set; }

    // New field, previsouly automatically generated by EF4
    public HashSet<Price> Prices { get; set; } 

    // New field, which allows me to query "all the PriceTables on which a Product appears"
    public IEnumerable<PriceTable> PriceTables 
        {
            get 
            { 
                return Prices.Select(p => p.PriceTables); 
            } 
        }
}