user66875
user66875

Reputation: 2608

Entity Framework : adding record with related data

I have a very simple Situation with 2 tables

public class Movie
{
    [Key]
    public Guid ID { get; set; }
    public string Name { get; set; }
    public byte[] Hash { get; set; }
    public int GenreID{ get; set; }
    [ForeignKey("GenreID")]        
    public virtual Genre genre{ get; set; }
}

and

public class Genre
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Now, in an import sequence I want to create new movies and link the Genre with the existing entries in the Genre table or create new Genre entries if they don't exist.

Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault(); 
if(genre!= null)
{
   m.GenreID= genre.GenreID;
}
else
{
   genre= new Genre();
   genre.Name = genreValue;
   db.Genres.Add(genre);
   var genreCreated= db.Genre.Where(g => g.Name== genreValue).FirstOrDefault();                                
   m.GenreID= genreCreated.GenreID;
}

Now the problem is, it doesn't work. The last line fails because genreCreated is null. Plus I think I must doing it wrong - it can't be that difficult in Entity Framework.

can anyone help me?

Upvotes: 1

Views: 973

Answers (2)

archil
archil

Reputation: 39491

db.Genres.Add(genre);

This does not send insert statement to database - this instructs entity framework that new record should be inserted when saving changes. Genre will be saved (and created id available) after you call db.SaveChanges(); As for now, you do not have save call, so genreCreated is null.

In your situation - fix is simple, you do not need to select genreCreated from db. Just setting m.Genre to new value should do the job

Movie m = new Movie();
m.ID = Guid.NewGuid();
IndexerContext db = new IndexerContext();
var genre = db.Genre.Where(g => g.Name== genreValue).FirstOrDefault(); 
if(genre! = null)
{
   m.GenreID = genre.GenreID;
}
else
{
   genre = new Genre();
   genre.Name = genreValue;
   m.Genre = genre;
}
db.SaveChanges(); //m.GenreID will automatically be set to newly inserted genre

Upvotes: 1

Ni3
Ni3

Reputation: 489

After the add statement you need to save it: Try

genre= new Genre();
genre.Name = genreValue;
db.Genres.Add(genre);
db.SaveChanges();

Upvotes: 1

Related Questions