【发布时间】:2016-06-19 22:51:16
【问题描述】:
我正在尝试为我的对象模型添加一个新条目,它具有很少的复杂类型,首先使用 EF 7 代码。但它不起作用并抛出异常。
型号:
public class Student
{
public int id {get; set;}
public string Name {get; set;}
public Address Address {get; set;} -> complex type
}
public class Address
{
public int Id {get;set;}
public string Location {get;set;}
}
代码优先代码:
class SchoolContext {
DbSet<Student> Students {get; set;}
DbSet<Address> Addresses {get; set;}
}
var context = new SchoolContext();
context.Students.Add(new Student { Id = 1, Name = "XYZ", Address = new Address { Id = 2, Location = "US" } } -> The add method has second parameter which says include dependent objects, and by default it is true.
context.SaveChanges();
这会引发异常:
{"INSERT 语句与 FOREIGN KEY 约束 \"FK_Student_Address_AddressId\" 冲突。冲突发生在数据库 \"School\"、表 \"dbo.Address\"、列 'Id' 中。\r\n语句已终止。"}
我认为这个错误意味着,地址对象在数据库中不存在,如果我先添加地址然后添加学生,它可以工作。但这只是太多的代码,因为在我的真实应用程序中,对象有很多复杂的类型。
理想情况下,这应该有效,但它没有。
【问题讨论】:
-
你试过在学生前面加地址吗?
-
你能不能贴出实际的类而不是伪代码?没有真正的代码可能会掩盖问题所在。您使用的是属性还是字段?等等……
-
@MaximeRouiller-MVP,如果我在学生对象之前专门添加地址对象,那么它工作正常。但我认为,如果我给实体一个学生对象,那么实体应该设法添加/更新所有子对象。这些都是我实际模型中的所有属性。\
-
我同意。但是您可以发布模型的实际代码还是使用字段?
-
版本 - "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"
标签: ef-code-first asp.net-core entity-framework-core