简体   繁体   English

使用Entity Framework代码优先的数据库问题

[英]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 . 现在,当我尝试将Cinema添加到我的Cinema数据库时,我得到了DbupdateException And it says 它说

Violation of PRIMARY KEY constraint 'PK_dbo.Movies'. 违反主键约束'PK_dbo.Movies'。 Cannot insert duplicate key in object 'dbo.Movies'. 无法在对象“ 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. 我没有添加名称为The Room的新电影,而是添加了具有新键的放映品。

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. 我建议您修改“显示”模型以使其具有电影FK的属性。 So you will set this property instead setting Movie property. 因此,您将设置此属性而不是设置Movie属性。

public class Showing
{
    public string MovieName { get; set; }
    [ForeignKye("MovieName")]
    public virtual Movie Movie { get; set; }
}

And then you set MovieName 然后设置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. 由于您使用的是上下文的新实例,因此当您对EF说添加您的放映时,它将尝试添加整个对象图,并且在这一刻,EF认为您的“来自放映对象的电影”是一个新实体,因此EF尝试也添加电影,您会收到此异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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