简体   繁体   中英

CRUD Operation with EntityFramework and MVC 5

I am relatively new to EntityFramework, ASP.NET and MVC 5.

Having followed the tutorial from here http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started

I would like to extend it by adding a One-To-Many relationship of Movie-Actor (that is an actor can be in many movies).

Thus i have these code in my Model folder:

Actor.cs

namespace MvcMovie.Models
{
    public class Actor
    {
        public int ActorId { get; set; }
        public String FirstName { get; set; }
        public String Address { get; set; }

        public ICollection<Movie> Movies { get; set; }
    }
}

Movie.cs

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }

        [StringLength(60, MinimumLength = 3)]
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }

        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [Required]
        [StringLength(30)]
        public string Genre { get; set; }

        [Range(1, 100)]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }

        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
        [StringLength(5)]
        public string Rating { get; set; }

        public int ActorId { get; set;}
        public Actor Actor { get; set; }
    }
}

MovieDBContext.cs

namespace MvcMovie.Models
{
    public class MovieDBContext : DbContext
    {
        public DbSet<Actor> Actors { get; set; }
        public DbSet<Movie> Movies { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Actor>().HasKey(p => p.ActorId);
            modelBuilder.Entity<Actor>().Property(c => c.ActorId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            modelBuilder.Entity<Movie>().HasKey(m => m.ID);
            modelBuilder.Entity<Movie>().Property(m => m.ID)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            modelBuilder.Entity<Movie>().HasRequired(p => p.Actor)
                .WithMany(m => m.Movies)
                .HasForeignKey(m => m.ActorId);
            base.OnModelCreating(modelBuilder);
        }
    }
}

Then i tried the following command on Package Manager

PM> Add-Migration ActorTable
PM> Update-Database

And get the following error: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Movies_dbo.Actors_ActorId". The conflict occurred in database "MOVIES_bd6a468e283a4100b6021adaf9911f7d", table "dbo.Actors", column 'ActorId'.

I have got a feeling that it has got something to do with my data seed (inside configuration.cs file)

protected override void Seed(MvcMovie.Models.MovieDBContext context)
        {
            context.Movies.AddOrUpdate(i => i.Title,
                new Movie
                {
                    Title = "When Harry Met Sally",
                    ReleaseDate = DateTime.Parse("1989-1-11"),
                    Genre = "Romantic Comedy",
                    Rating = "PG",
                    Price = 7.99M
                },

        }

Can someone suggest me to the right direction. Thanks

ps: I have MovieController and its corresponding View setup (from earlier steps that i did as shown in the tutorial).

In addition to Mak's answer:

This article contain useful help as well, especially at the Add a Migration and Update the Database section.

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

Following lines in your OnModelCreating says that, Actor is required in Movie

modelBuilder.Entity<Movie>().HasRequired(p => p.Actor)
            .WithMany(m => m.Movies)
            .HasForeignKey(m => m.ActorId);

For successfully update database you can change your seed method like this :

context.Movies.AddOrUpdate(i => i.Title,
            new Movie
            {
                Title = "When Harry Met Sally",
                ReleaseDate = DateTime.Parse("1989-1-11"),
                Genre = "Romantic Comedy",
                Rating = "PG",
                Price = 7.99M,
                Actor = new Actor() { FirstName = "Actor1", Address = "Address1"}
            });

Hope this helps.

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