我有两张表,它们之间有关系。
以下是我的模特:
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)
);
当我执行Update-Database时,我得到一个“对象引用未设置为对象的实例”。错误。
为什么呢?这些表存在于数据库中,也就是关系。 我在这里缺少什么?
答案 0 :(得分:3)
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 }
}
});