在 Entity Framework 6 Code First 中创建一对一关系时出错
Error creating One-to-One relationships in Entity Framework 6 Code First
我正在按照本教程建立一对一关系,但无济于事。
http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
这是我的快速模型
public class Information
{
public int InformationId { get; set; }
public string Thing1 {get; set;}
public string Thing2 { get; set;}
public ICollection<Item> Items { get; set; }
public Account Account { get; set; }
}
public class Account
{
[Key, ForeignKey("Information")]
public int InformationId { get; set; }
public string Thing1 { get; set; }
public Information Information { get; set; }
}
然后我针对它执行此操作
var information = new List<Information>{
new Information(){
Thing1 = "this",Thing2="that"
}
};
information.ForEach(s => context.Information.Add(s));
context.SaveChanges();
var account = new List<Account>{
new Account(){Thing1="one"}
};
account.ForEach(s => context.Accounts.Add(s));
context.SaveChanges();
错误
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Account_dbo.Information_InformationId\". The conflict occurred in database \"TestEF\", table \"dbo.Information\", column 'InformationId'.\r\nThe statement has been terminated."}
先存账号,再存信息
var account = new List<Account>{
new Account(){Thing1="one"}
};
account.ForEach(s => context.Accounts.Add(s));
context.SaveChanges();
var information = new List<Information>{
new Information(){
Thing1 = "this",Thing2="that"
}
};
information.ForEach(s => context.Information.Add(s));
context.SaveChanges();
我正在按照本教程建立一对一关系,但无济于事。 http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
这是我的快速模型
public class Information
{
public int InformationId { get; set; }
public string Thing1 {get; set;}
public string Thing2 { get; set;}
public ICollection<Item> Items { get; set; }
public Account Account { get; set; }
}
public class Account
{
[Key, ForeignKey("Information")]
public int InformationId { get; set; }
public string Thing1 { get; set; }
public Information Information { get; set; }
}
然后我针对它执行此操作
var information = new List<Information>{
new Information(){
Thing1 = "this",Thing2="that"
}
};
information.ForEach(s => context.Information.Add(s));
context.SaveChanges();
var account = new List<Account>{
new Account(){Thing1="one"}
};
account.ForEach(s => context.Accounts.Add(s));
context.SaveChanges();
错误
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Account_dbo.Information_InformationId\". The conflict occurred in database \"TestEF\", table \"dbo.Information\", column 'InformationId'.\r\nThe statement has been terminated."}
先存账号,再存信息
var account = new List<Account>{
new Account(){Thing1="one"}
};
account.ForEach(s => context.Accounts.Add(s));
context.SaveChanges();
var information = new List<Information>{
new Information(){
Thing1 = "this",Thing2="that"
}
};
information.ForEach(s => context.Information.Add(s));
context.SaveChanges();