我有3张桌子,
public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>
{
protected override void Seed(DatabaseContext context)
{
base.Seed(context);
//
context.Cities.Add(
new Cities() { CityId = 1, CityDesc = "Tel Aviv" }
);
context.Cities.Add(
new Cities() { CityId = 2, CityDesc = "Ramat Gan" }
);
context.Streets.Add(
new Streets() { StreetId = 1, CityId = 1, StreetDesc = "Pinkas"}
);
context.Streets.Add(
new Streets() { StreetId = 2, CityId = 2, StreetDesc = "Bialik" }
);
context.Parkings.Add(
new Parkings() { ParkStreetId = 1, ParkCityId = 1, StartDate = "2018-01-17", EndDate = "2018-01-17" }
);
context.Parkings.Add(
new Parkings() { ParkStreetId = 2, ParkCityId = 2, StartDate = "2018-01-17", EndDate = "2018-01-17" }
);
context.SaveChanges();
}
}
这个想法是 - 城市有很多街道,街道有很多停车场。 最终的目标是带来一个包含以下内容的Parkings对象:
[dbo.Parkings.ParkId,dbo.Parkings.ParkStartDate,dbo.Parkings.ParkEndDate,dbo.Cities.CityDesc,dbo.Streets.StreetDesc]
(进入新停车场的表格将包含:StartDate,EndDate,CityDesc,StreetDesc)
我首先尝试使用数据为数据库设定种子:
"exceptionMessage": "The ForeignKeyAttribute on property 'Cities' on type 'BeraleBack.Models.entites+Parkings' is not valid. The foreign key name 'CityId' was not found on the dependent type 'BeraleBack.Models.entites+Parkings'. The Name value should be a comma separated list of foreign key property names.",
"exceptionType": "System.InvalidOperationException",
但是我收到了这个错误:
{{1}}
我首先要知道,如果我的配置是基于我提供的信息是正确的。 第二,我应该如何种下它?
我是一个完整的菜鸟,并没有遇到任何有用的教程..
非常感谢!!
答案 0 :(得分:0)
当我更频繁地使用DBFirst时,请耐心等待,但看起来您的实体框架无法找到您的外键属性。
将Parkings
与Streets
public class Streets
{
[Key]
public int StreetId { get; set; }
public int CityId { get; set; } //Property which foreign key is assoctiated with
[Required]
public string StreetDesc { get; set; }
[ForeignKey("CityId")]
public virtual Cities Cities { get; set; }
}
但是Parkings
实体
public class Parkings
{
[Key]
public int ParkId { get; set; }
[Required]
public string StartDate { get; set; }
[Required]
public string EndDate { get; set; }
public int ParkStreetId { get; set; }
public int CityId{ get; set; }
[ForeignKey("CityId")]
public virtual Cities Cities { get; set; }
}