Populate associated entities on DBContext Find

时间:2015-10-29 15:56:13

标签: c# asp.net-mvc entity-framework

I have a Product which needs to have some fields in multiple languages. Therefore I have made a ProductLanguage table which has the composite key and language specific fields (ProductID, LanguageID, Name).

In my Product class I tried something like this:

[Table("Product")]
public class Product
{
    DBContext db = new DBContext();

    public Product()
    {
        this.Multimedias = new List<Multimedia>();
        this.ProductLanguages = new List<ProductLanguages>();
        this.ProductLanguage = db.ProductLanguages.Find(this.ID, Global.Language) ?? new ProductLanguage();
    }

    public int ID { get; set; }
    public string Code { get; set; }
    public virtual ICollection<Multimedia> Multimedias { get; set; }
    public virtual ICollection<ProductLanguage> ProductLanguages { get; set; }

    [NotMapped]
    public virtual ProductLanguage ProductLanguage { get; set; }
}

So I could immediately access the language specific fields without needing to go through the collection - the problem is the object obviously doesn't have the ID yet.

Is there any way so when I do

Product product = db.Products.Find(id);

in the controller it will automatically populate my ProductLanguage property?

3 个答案:

答案 0 :(得分:1)

您可以在Get for the property中移动ProductLanguage的作业。

答案 1 :(得分:0)

您不需要属性

[NotMapped]
public virtual ProductLanguage ProductLanguage { get; set; }

ProductLanguages集合将在您点击时通过延迟加载填充。你需要的是这样的方法,它将通过id:

返回ProductLanguage
public ProductLanguage GetProductLanguageById(int id)
{
    if (ProductLanguages != null)
    {
        return ProductLanguages.Where(pl => pl.Id == id).FirstOrDefault();
    }
}

答案 2 :(得分:0)

这并不能证实我以前见过的任何练习/用法..,不管我会考虑非常!!非常!! 糟糕的做法。不要在实体(表)中创建上下文的实例。

另外你为什么要这样做...我建议你阅读Lazy和eager loading。

引用 “在控制器中它会自动填充我的ProductLanguage属性吗?”

是....使用急切加载。

Product product = db.Products.Include("ProductLanguage").Find(id);

但我强烈建议您不要在实体的初始化中执行所有其他奇怪的操作。

DBContext db = new DBContext();
Product product = db.Products.Include("ProductLanguage").Find(id);