i have following classes:
public class cartitem { public long id { get; set; } public int quantity { get; set; } public product product { get; set; } } public class product { public long id { get; set; } public string title { get; set; } public decimal price { get; set; } }
i have following configuration:
modelbuilder.entity<cartitem>().hasrequired(x => x.product).withmany().map(x => x.mapkey("productid"));
i trying ensure whenever retrieve cartitem database there join on product table can access product properties not other way around.
i want able do:
string title = cartitem.product.title
using configuration have gives me object reference not set instance of object exception.
short answer: solve problem, make product
property virtual
.
in-depth:
first, don't need join this. ef works fine lazy loading (you need virtual
modifier)
second, can fetch product eagerly, using include
extension method. example:
var cartitem = context.cartitems.include(x => x.product) .where(/*some condition*/).tolist();
...but can't configure default behavior (nor idea usually)
third, many-to-one relationship, not one-to-one (a product has many related cartitems)
Comments
Post a Comment