Add/insert 包含复杂类型的新条目 Entity Framework 7 代码优先

Add/insert a new entry containing complex type in Entity Framework 7 Code first

我正在尝试首先使用 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();

这会引发异常:

{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Student_Address_AddressId\". The conflict occurred in database \"School\", table \"dbo.Address\", column 'Id'.\r\nThe statement has been terminated."}

我认为这个错误的意思是,Address 对象在数据库中不存在,如果我先添加地址,然后再添加 Student,就可以了。但这只是代码太多,因为在我的实际应用程序中对象有很多复杂的类型。

理想情况下这应该有效,但实际上无效。

基于this bug report,您应该在之前添加项目。

被认为是as-designed。至少到 RC2.