Reputation: 113
I created a database using code-first method. Now when I try to add a showing to my Cinema
database I get an DbupdateException
. And it says
Violation of PRIMARY KEY constraint 'PK_dbo.Movies'. Cannot insert duplicate key in object 'dbo.Movies'. The duplicate key value is (The Room)
I don't understand why. I'm not adding a new movie with the name The Room
, I'm adding a showing with a new key.
namespace Cinema3Project.Tables
{
class Showing
{
[Key]
public int Number { get; set; }
public DateTime Date { get; set; }
public TimeSpan Time { get; set; }
public virtual Movie Movie { get; set; }
public virtual Screen Screen { get; set; }
}
}
class Movie
{
[Key]
public string Name { get; set; }
public string Director { get; set; }
public string Genre { get; set; }
public string Language { get; set; }
public int LengthMin { get; set; }
}
Inserting method looks like this:
using (var db = new CinemaContext())
{
db.Showings.Add(showing);
db.SaveChanges();
}
Upvotes: 0
Views: 296
Reputation: 6229
I would suggest that you modify your Showing model to have the property that is the Movie FK. So you will set this property instead setting Movie property.
public class Showing
{
public string MovieName { get; set; }
[ForeignKye("MovieName")]
public virtual Movie Movie { get; set; }
}
And then you set MovieName
//showing.Movie do not set this property
showing.MovieName = movie.Name;
using (var db = new CinemaContext())
{
db.Showings.Add(showing);
db.SaveChanges();
}
Since you are using a new instance of your context, when you say to EF add your showing, it will try to add entire object graph, and in this moment, EF thinks that your Movie from showing object is a new entity, so EF try to add Movie too, and you get this exception.
Upvotes: 1