1

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?

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

Comments

1

After the add statement you need to save it: Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.