EF Core save list of entities with navigation property

asp.net-core c# entity-framework entity-framework-core

Question

I'm building an WebApi using .Net Core with EF Core (2.0) and found a problem when saving a list of entities.

The problem is that I have a navigation property in my entity, something like:

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

To save a single entity I'm using this to avoid trying to insert a Course that already exists:

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

I find it ugly and would like to know a better way, but it works. Sometimes I allow the API to receive a list of Students and it should save them all. Calling Attach raises an exception if called twice on the same Course.

All I wanted was to EF Core to save only the Student entity with the correct foreign key, I want nothing done in the Course entity in the database. What is the best way to accomplish that?

1
0
1/30/2018 11:56:42 AM

Popular Answer

I find it ugly and would like to know a better way

Yes, there is DTO . They are just like data models we create.

So, you will need to create a CreateStudentDto which you will use during creation.

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

So, when you will get the input or map your input from entity class to createmodel, Mapper/Input will auto strip the Course from your create.

0
1/30/2018 12:16:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow