首先在Entity Framework 7 Code中添加/插入包含复杂类型的新条目

问题描述 投票:2回答:1

我正在尝试为我的对象模型添加一个新条目,它具有很少的复杂类型,首先使用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 \“,table \”dbo.Address \“,列'Id'。\ r \ n语句已终止。“}

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

理想情况下,这应该有效,但事实并非如此。

ef-code-first asp.net-core entity-framework-core
1个回答
2
投票

基于this bug report,您应该先添加项目。

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

© www.soinside.com 2019 - 2024. All rights reserved.