Entity Framework insert many to many record with existing parents

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

Question

I have 3 tables: Video, Course, and CourseVideo. I want to do an insert into CourseVideo.

The Video may or may not have an existing record, but when it does I want to use the existing record and NOT create a new record.

My code looks like this:

var video = db.Videos.SingleOrDefault(c => c.Link.Equals(link));

if(video == null)
{
    video = new Video { ... };
    db.Videos.Add(video);
    db.SaveChanges();
}

var course = db.Courses.Include("Videos").Single(c => c.ID == courseID);
course.Videos.Add(video);
db.SaveChanges();

This adds a record in the many-to-many table (CourseVideo) but it also creates a new record in the Video table.

How do I prevent the insert into the Video table if it already exists?

1
5
4/26/2015 6:25:39 PM

Popular Answer

To prevent the insert into the Video table if it already exists, the added video must be in the context. You don't need to call savechanges() for the new video.

0
2/10/2016 1:24:47 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