我是一名綠色的asp.net開發人員,我正在使用最新的實體框架與我的項目。我遇到了一個問題,我的數據庫採用自動生成的值(我認爲)。這是確切的錯誤。INSERT語句與FOREGIGN KEY約束衝突
下面的代碼:
public class Address
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
// some more properties
}
public class ApplicationUser : IdentityUser
{
[ForeignKey("Address")]
public int AddressId { get; set; }
public Address Address { get; set; }
// some more properties
}
public class Shelter
{
[Required]
[ForeignKey("Address")]
public int AddressId { get; set; }
public Address Address { get; set; }
// some more properties
}
//seed
private void CreateShelters()
{
EntityEntry<Address> MspcaAddress = DbContext.Addresses.Add(new Address()
{
Street = "350 S Huntington Ave",
City = "Jamaica Plain",
State = "MA",
AreaCode = "02130",
Latitude = 42.3228928,
Longititude = -71.11120540000002
});
EntityEntry<Address> BostonAnimalCareAndControlAddress = DbContext.Addresses.Add(new Address()
{
Street = "26 Mahler Rd",
City = "Roslindale",
State = "MA",
AreaCode = "02131",
Latitude = 42.2943377,
Longititude = -71.12153390000003
});
EntityEntry<Address> AnimalRescueLeagueOfBostonAddress = DbContext.Addresses.Add(new Address()
{
Street = "10 Chandler St",
City = "Boston",
State = "MA",
AreaCode = "0S2116",
Latitude = 42.3470486,
Longititude = -71.06976929999996
});
EntityEntry<Shelter> Mspca = DbContext.Shelters.Add(new Shelter()
{
Name = "MCSPA",
AddressId = MspcaAddress.Entity.AddressId
});
EntityEntry<Shelter> BostonAnimalCareAndControl = DbContext.Shelters.Add(new Shelter()
{
Name = "Boston Animal Care And Control",
AddressId = BostonAnimalCareAndControlAddress.Entity.AddressId
});
EntityEntry<Shelter> AnimalRescueLeagueOfBoston = DbContext.Shelters.Add(new Shelter()
{
Name = "Animal Rescue League Of Boston Address",
AddressId = AnimalRescueLeagueOfBostonAddress.Entity.AddressId
});
DbContext.SaveChanges();
}
我試圖重新創建數據庫,查看是否有數據不一致/表的問題,但我仍然得到錯誤。有任何想法嗎?
舉一個賞金並不會讓問題變得更好。您仍然需要提供[mcve]以避免後續評論,例如*我仍然收到錯誤... *。由於異常消息清楚地表明問題不在所提供的代碼中(儘管很可能它有相同的問題),但是在插入'ApplicationUser'的代碼中。 –
您提供的代碼根本不會將新的'ApplicationUser'添加到數據庫,而錯誤表明外鍵被違反了'ApplicationUser'。你確定你正在調試和共享相同的代碼。如果發佈的代碼不正確,請重新查看發佈的代碼。 –