【问题标题】:Many to one configuration using EF 4.1 code first多对一配置首先使用 EF 4.1 代码
【发布时间】:2011-05-01 00:00:28
【问题描述】:

我有以下课程:

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; }
}

我目前有以下配置:

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

我试图确保每当我从数据库中检索到 caritem 时,产品表上都会有一个联接,这样我就可以访问产品属性,但不能反过来。

我基本上希望能够做到:

string title = cartItem.Product.Title

使用我的配置给了我一个未设置为对象异常实例的对象引用。

【问题讨论】:

    标签: ef-code-first many-to-one


    【解决方案1】:

    简短回答:要解决您的问题,请将Product 属性设为virtual

    深入:

    首先,您不需要加入来执行此操作。 EF 可以很好地处理延迟加载(您需要 virtual 修饰符)

    其次,您可以使用Include 扩展方法急切地获取产品。示例:

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

    ...但是您不能将其配置为默认行为(通常也不是一个好主意)

    第三,这是多对一的关系,而不是一对一的(一个产品有很多相关的 CartItems)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多