I have a database-first application, with entities Promotion
and Product
, and the navigation property Promotion.Products
. There are other navigation properties on Promotion. I want to ignore these other navigation properties in one of my methods, and load only the promotions, each with a collection of products (code below is simplified).
If I use lazy loading:
// Lazy Loading true by default
// ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions select p;
data.First().Products contains 1 Product.
If I use eager loading:
ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions.Include(p => p.Products)
select p;
data.First().Products is empty.
I have used eager loading elsewhere with success. I don't know why it isn't working for me here.
I realize that I can simply use linq joins to get the desired result, but this will complicate my class and cause some duplicated code. I can also force it using:
ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions
select new {
Promo = p,
Products = p.Products
};
which gives 1 item in data.First().Promo.Products
or data.First().Products
, but I'd rather do it "by the book".
Entity Code
public static Promotion CreatePromotion(global::System.Int32 id, ...)
{
Promotion promotion = new Promotion();
promotion.Id = id;
...
return promotion;
}
...
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("MyDataModel", "PromotionsProducts", "Product")]
public EntityCollection<Product> Products
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product>("MyDataModel.PromotionsProducts", "Product");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product>("MyDataModel.PromotionsProducts", "Product", value);
}
}
}