Many to one configuration using EF 4.1 code first

北战南征 提交于 2019-12-13 07:04:12

问题


I have the 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 currently have the following configuration:

modelBuilder.Entity<CartItem>().HasRequired(x => x.Product).WithMany().Map(x => x.MapKey("ProductId"));

I am trying to ensure that whenever I retrieve a cartitem from the database there will be a join on the product table so I can access the product properties but not the other way around.

I basically want to be able to do:

string title = cartItem.Product.Title

using the configuration I have gives me an Object reference not set to an instance of an object exception.


回答1:


Short answer: to solve your problem, make the Product property virtual.

In-depth:

First, you don't need a join to do this. EF works fine with lazy loading (you need the virtual modifier)

Second, you can fetch the Product eagerly, using the Include extension method. Example:

var cartItem = context.CartItems.Include(x => x.Product)
                      .Where(/*some condition*/).ToList();

...but you can't configure this to be the default behavior (nor is it a good idea usually)

Third, this is a many-to-one relationship, not one-to-one (a Product has many related CartItems)



来源:https://stackoverflow.com/questions/5845429/many-to-one-configuration-using-ef-4-1-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!