【问题标题】:EF Core save list of entities with navigation propertyEF Core 保存具有导航属性的实体列表
【发布时间】:2018-01-30 20:16:30
【问题描述】:

我正在使用 .Net Core 和 EF Core (2.0) 构建 WebApi,但在保存实体列表时发现了问题。

问题是我的实体中有一个导航属性,例如:

public class Student
{
    public Course Course {get; set;}
}

为了保存单个实体,我使用它来避免尝试插入已经存在的课程:

student.Course = _context.Courses.Attach(student.Crouse).Entity

我觉得它很丑,想知道一个更好的方法,但它确实有效。有时我允许 API 接收Students 的列表,它应该将它们全部保存。如果在同一课程上调用两次,调用 Attach 会引发异常。

我想要的只是 EF Core 只保存具有正确外键的 Student 实体,我不想在数据库中的 Course 实体中做任何事情。实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: c# entity-framework asp.net-core entity-framework-core


    【解决方案1】:

    我觉得它很丑,想知道更好的方法

    是的,有 DTO 。它们就像我们创建的数据模型。

    因此,您需要创建一个将在创建期间使用的 CreateStudentDto。

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        ...
        //this won't contain the -> public Course Course {get; set;}
    }
    

    因此,当您从实体类获取输入或将输入映射到 createmodel 时,Mapper/Input 将自动从您的创建中剥离课程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多