我有两个表,它们之间有关系。
这是我的模型:
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)
);
当我执行更新数据库时,会收到“对象引用未设置为对象的实例”。错误。
为什么?表存在于数据库中,关系也存在。
我在这里想念什么?
最佳答案
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 }
}
});