[asp.net-mvc]MVC 种子不会在数据库中的数据

发布时间: 2017/3/25 4:55:06
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有两个表与它们之间的关系。

下面是我的模型︰

public  class Locations
{
  [Key]
  public int LocationID { get; set; }

  [Required(ErrorMessage = "This field is required!")]
  [MaxLength(50, ErrorMessage = "The name is too long. Max. 50 characters allowed!")]
  [Display(Name = "Location name:")]
  public string Name { get; set; }

  public int Position { get; set; }

  public virtual LocationType LocationType { get; set; }

}

public class LocationType
{
  [Key]
  public int LocationTypeID { get; set; }

  [Required(ErrorMessage = "This field is required!")]
  [MaxLength(25, ErrorMessage = "The name is too long. Max. 25 characters allowed!")]
  [Display(Name = "Location type:")]
  public string Name { get; set; }

  public int Position { get; set; }

  public int HasChoicesOrInput { get; set; } 

  public virtual ICollection<Locations> Locations { get; set; }
}

我的 configuration.cs 文件中,我有以下的种子︰

context.LocationType.AddOrUpdate(a => a.LocationTypeID,
  new LocationType
  {
    Name = "AAAAA",
    HasChoicesOrInput = 1,
    Position = 1,
    Locations = { new Locations { Name = "1111111", Position = 1 },
                    new Locations { Name = "2222222", Position = 2 }
                }
  });

表定义︰

CREATE TABLE [dbo].[Locations] (
[LocationID]                  INT           IDENTITY (1, 1) NOT NULL,
[Name]                        NVARCHAR (50) NOT NULL,
[Position]                    INT           NOT NULL,
[LocationType_LocationTypeID] INT           NULL,
CONSTRAINT [PK_dbo.Locations] PRIMARY KEY CLUSTERED ([LocationID] ASC),
CONSTRAINT [FK_dbo.Locations_dbo.LocationTypes_LocationType_LocationTypeID] FOREIGN KEY ([LocationType_LocationTypeID]) REFERENCES [dbo].[LocationTypes] ([LocationTypeID])
);

CREATE TABLE [dbo].[LocationTypes] (
[LocationTypeID]    INT           IDENTITY (1, 1) NOT NULL,
[Name]              NVARCHAR (25) NOT NULL,
[Position]          INT           NOT NULL,
[HasChoicesOrInput] INT           NOT NULL,
CONSTRAINT [PK_dbo.LocationTypes] PRIMARY KEY CLUSTERED ([LocationTypeID] ASC)
);

当我更新数据库时,我得到一个"对象引用不设置到对象的实例"错误。

为什么呢?在数据库中,关系也存在的表。 在这里我错过了什么?

解决方法 1:

Locations初始化程序

new LocationType
{
  Name = "AAAAA",
  HasChoicesOrInput = 1,
  Position = 1,
  Locations = { new Locations { Name = "1111111", Position = 1 },
                new Locations { Name = "2222222", Position = 2 }
            }
});

不会创建 Locations 集合。它调用属性 getter 获得现有的 Locations 收集和调用 Add 上它。因为你永远不会分配任何东西给该属性,你得到 NullReferenceException

此语法是 C# 语言规范中,节 7.6.10.2 对象初始值设定项中所述︰

等号后面指定集合初始值设定项的成员初始值设定项是集合的嵌入式的初始化。而不是对该字段或属性分配一个新的集合,给出了初始值设定项中的元素添加到引用的字段或属性的集合。 应该创建一个集合 (例如一个列表或数组) 的一个新实例,并将其分配给 Locations 属性初始值设定项中︰

new LocationType
{
  Name = "AAAAA",
  HasChoicesOrInput = 1,
  Position = 1,
  Locations = new List<Locations> 
  { 
      new Locations { Name = "1111111", Position = 1 },
      new Locations { Name = "2222222", Position = 2 }
  }
});
官方微信
官方QQ群
31647020