Entity Framework insert many to many record with existing parents

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

Question

I've got 3 tables.Video , Course , andCourseVideo I want to insert anything intoCourseVideo .

The Video may or may not already have a record, but if it does, I want to use that record rather than making a new one.

This is how my code looks:

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();

With this, a record is added to the many-to-many table (CourseVideo ) yet it also adds a fresh entry to theVideo table.

How can I stop the insert from theVideo if the table already exists?

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

Popular Answer

ZZZ_tmp
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