6

我正在尝试在 entityframework5 codefirst 方式上使用我的实体创建一个 DbContext。我有品牌、类别和产品。

但是当我尝试获取ProductBrand并且Category字段为空时。Category是可选的,但Brand不是。所以至少必须设置品牌字段。我尝试了下面的代码。有什么我想念的吗?

    public DbSet<Brand> Brands { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Brand>()
            .HasMany(b => b.Products)
            .WithRequired(p => p.Brand)
            .HasForeignKey(p => p.BrandId);

        modelBuilder.Entity<Category>()
            .HasMany(c => c.Products)
            .WithOptional(p => p.Category)
            .HasForeignKey(p => p.CategoryId);
    }

在 MVC 控制器端:

    using (var db = new InonovaContext())
    {
        var product = db.Products.Single(p => p.Id == id);
        model.Description = product.Description;
        model.ImageUrl = product.ImageUrl;
        model.Name = product.Name;
        model.BreadCrumb = product.Brand.Name + " / " + product.Category == null ? "" : (product.Category.Name + " / ") + product.Name; // Here Brand and Category are null
    }

产品类别如下

public class Product
{
    public int Id { get; set; }
    public int BrandId { get; set; }
    public virtual Brand Brand { get; set; }
    public string Name { get; set; }
    public int? CategoryId { get; set; }
    public virtual Category Category { get; set; }
    public string ImageUrl { get; set; }
    public string Description { get; set; }
}

品牌类如下:

public class Brand
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ThumbLogoImageUrl { get; set; }
    public string Description { get; set; }
    public ICollection<Product> Products { get; set; }
}

谢谢。

4

1 回答 1

6

如果您尚未将 Brand 和 Category 声明为虚拟,则 Brand 和 Category 属性的延迟加载将不起作用。

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual Brand Brand { get; set; }
    public int BrandId { get; set; }

    public virtual Category Category { get; set; }
    public int? CategoryId { get; set; }
}

有关延迟加载和急切加载的更多信息,请参阅此内容。

于 2013-09-22T15:23:07.487 回答