简体   繁体   English

实体框架核心:如何添加复合对象?

[英]Entity Framework Core: How to add a composite object?

There is the following composite object, for example: 有以下复合对象,例如:

public class Parent
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("ChildRefId")]
    public Guid ChildId { get; set; }

    public Child Child { get; set; }
}

public class Child
{
    [Key]
    public Guid Id { get; set; }

    [ForeignKey("ParentRefId")]
    public int ParentId { get; set; }

    public Parent Parent { get; set; }
}

Parent and Child has one-to-one relation: ParentChild有一对一的关系:

modelBuilder.Entity<Parent>()
    .HasOne(parent => parent.Child)
    .WithOne(child => child.Parent)
    .WillCascadeOnDelete();

I try to create new Parent with Child and save it in the DB: 我尝试使用Child创建新的Parent并将其保存在DB中:

var parent = new Parent { Child = new Child() };
dbContext.Parents.Add(parent);
dbContext.SaveChanges(); //<-- Exception!

...and get the following exception: ...并获得以下异常:

System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Parent_Child_ChildId". The conflict occurred in database "MyDatabase", table "dbo.Child", column 'Id'.

If I use the db context to create a child it works fine: 如果我使用db上下文创建一个子,它工作正常:

var child = dbContext.Childs.Add(new Child());
var parent = new Parent { Child = child };
dbContext.Parents.Add(parent);
dbContext.SaveChanges(); //<-- It works fine

Question #1: I can easily add new entities to a nested collections without using context for create it. 问题1:我可以轻松地将新实体添加到嵌套集合中,而无需使用上下文来创建它。 But it not works for one-to-one relation. 但它不适用于一对一的关系。 For example: 例如:

var parent = new Parent();
parent.Grandparents.Add(new Grandparent();
dbContext.Parents.Add(parent);
dbContext.SaveChanges(); //<-- It works fine and parent with one new grandparent were created!

Why? 为什么?

Question #2: Please, describe me what I do wrong and how I can save new parent with a child without context to create a child (like nested collections)? 问题2:请描述一下我做错了什么以及如何在没有上下文的情况下保存新父母以创建孩子(如嵌套馆藏)?

Thank you! 谢谢!

This error is occurring only for the beta-8 version of EF. 此错误仅针对EF的beta-8版本发生。 After I was updated EF to the rc1-final version error disappeared. 在我更新EF后, rc1-final版本错误消失了。 It may be explained there is no graph tracking on the beta-8 version yet. 可以解释的是,目前尚未对beta-8版本进行图形跟踪。

You can find more detailed information here . 您可以在此处找到更多详细信息。

You should remove the fluent syntax declaration (modelBuilder.Entity ...), it's not required in this instance. 您应该删除流畅的语法声明(modelBuilder.Entity ...),在这个实例中不需要它。

You also need to use your context to create objects, and you should be specifying the Id key values. 您还需要使用上下文来创建对象,并且应该指定Id键值。 It's common to use Int's for keys- coupled with an automated database insert annotation that generates the keys for you. 通常使用Int作为键 - 与自动数据库插入注释相结合,为您生成键。 eg 例如

public class Child {
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[ForeignKey("ParentRefId")]
public int ParentId { get; set; }

public Parent Parent { get; set; }
}

You should also use your context to create model objects something like: 您还应该使用上下文来创建模型对象,例如:

using(MyDbContext db = new MyDbContext()) {
  Child child = db.Childs.Create();
  Parent parent = db.Parents.Create();
  child.Parent = parent;
}
db.SaveChanges();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用复合键在 model 的实体框架核心中获取单个实体? - How to get single entity in Entity Framework Core of model with composite key? 如何在 Entity Framework Core 的复合键中配置与常量的关系? - How to configure relationship with a constant in the composite key for Entity Framework Core? 实体框架核心-如何正确使用复合键映射关系? - Entity Framework Core - How to correctly map relationships with composite key? 实体框架核心查找和复合键 - Entity Framework Core Find and Composite Key 使用复合键更新记录 - Entity Framework Core - Update Record with Composite Key - Entity Framework Core 如何在Entity Framework 6的数据批注中添加复合外键 - How to add composite foreign key in data annotation for Entity Framework 6 实体框架核心:组合表请求(组合键) - Entity Framework Core: Request for Composite Table (Composite Key) 如何使用实体框架核心 3.1.1 为拥有的实体类型设置复合主键? - How to set the composite primary key for owned entity types using entity framework core 3.1.1? 如何在Entity Framework中查找具有组合键的实体 - How to find entity with composite key in Entity Framework 如何使用 Entity Framework Core 在不同的表中多次添加 object [跟踪错误] - How to add an object multiple times in different tables with Entity Framework Core [Tracking error]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM