【问题标题】:Null Foreign Key in Entity Framework code first实体框架代码中的空外键优先
【发布时间】:2018-09-25 22:03:28
【问题描述】:

我有一个经典场景产品-品牌关系。我的课也是这样。

公开课产品 { 公共 int ProductID { 获取;放; } 公共字符串产品名称 { 获取;放; } 公共小数价格 { 得到;放; } 公共字符串 PreDescription { 获取;放; } 公共诠释?品牌 ID { 获取;放; } //自有品牌品牌; 公共虚拟品牌 Brand { 得到; //{ if (this.Brand == null) Brand = new Brands();返回品牌; } 放; //{ 品牌 = 价值; } } } 公共类品牌 { 公共 int BrandID { 获取;放; } 公共字符串 BrandName { 获取;放; } 私有列表产品; 公共虚拟列表产品 { get{ if (this.products == null) products = new List();退货; } 设置{产品=价值; } } }

像这样映射。

公共类 ProductsMap : EntityTypeConfiguration{ 公共 ProductsMap() { ToTable("产品"); HasKey(p => p.ProductID).Property(p => p.ProductID) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.HasOptional(p => p.Brand).WithMany(b => b.Products); } } 公共类 BrandsMap : EntityTypeConfiguration { 公共品牌地图() { ToTable("品牌"); HasKey(b => b.BrandID).Property(b => b.BrandID) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); } }

我有两个方法,GetAll(),GetByID() Product 表上的某些行具有 Null 值。

当我尝试运行 GetAll 方法时,它会抛出 Null 异常(某些产品的品牌返回 null),但是通过 GetByID() 获取的所有产品都不会抛出任何异常?

【问题讨论】:

  • GetAll() 长什么样子...

标签: c# entity-framework-4


【解决方案1】:

虽然从 dB 获取值包括关联表(产品)以及父表(品牌)。

例子:

var brands=context.Brand.include("Products");

【讨论】:

  • 我仍然在 GetAll() 方法上收到此错误。如果返回的数据中有null值和int值,则抛出异常。
  • 我认为BrandID 不应该是可选的。将其更改为public int BrandID { get; set; }
猜你喜欢
  • 2011-08-05
  • 1970-01-01
  • 2012-05-10
  • 2015-02-24
  • 2021-01-05
  • 2011-08-05
  • 1970-01-01
相关资源
最近更新 更多