简体   繁体   中英

Using Entity Framework code-first database issue

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM