加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Entity Framework 5 codefirst /必需和可选的外键关系为nu

发布时间:2020-12-15 08:43:21 所属栏目:百科 来源:网络整理
导读:我想在entityframework5 codefirst方式上用我的entites创建一个DbContext.我有品牌,类别和产品. 但是当我尝试获取产品时,它的品牌和类别字段为空.类别是可选的,但品牌不是.所以至少必须设置品牌领域.我试过下面的代码.有什么我想念的吗? public DbSetBrand
我想在entityframework5 codefirst方式上用我的entites创建一个DbContext.我有品牌,类别和产品.

但是当我尝试获取产品时,它的品牌和类别字段为空.类别是可选的,但品牌不是.所以至少必须设置品牌领域.我试过下面的代码.有什么我想念的吗?

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

谢谢.

解决方法

如果您尚未将品牌和类别声明为虚拟,则延迟加载品牌和类别属性将不起作用.
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; }
}

有关延迟和急切加载的更多信息,请参阅this.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读