Code First entity framework and foreign keys

c# database entity-framework

Question

Imagine I have a database created by code first that looks like this.

Movie (table)
ID int PK
MoveiName nvarchar(100)

Actor (table)
ID int PK
ActorName nvarchar(100)
Movie_ID int FK

These are the models I would have used, obviously not exactly like this but you'll get my point.

class Movie
{  
    int ID{get;set;}
    string MovieName {get;set;}
    List<Actor> Actors {get;set}
}

class Actor
{
    int ID{get;set}
    string Actorname{get;set}
    Movie Movie{get;set;}
    int Move_ID{get;set;}
}

Database first enables me to query the movie from an actor but also lets me set the forgien key property of the actor to update the database. I cant do this in code first because the foreign key isnt in the model only the object. I prefer not to get the Movie object and set the property, if i know the id of my movie I'd rather just set the foreign key without the call to get the movie.

Make sense? lol

I want to use codefirst and entity migrations but i want the same ability as database first to set a foreign key on an object.

Cheers for the help :-D

1
3
11/15/2013 1:32:18 PM

Accepted Answer

First change your code to this

public class Movie
{  
   int ID{ get; set; }
   string MovieName {get; set; }
   List<Actor> Actors {get; set; }
}

 public class Actor
 {
    int ID{get;set}
    string ActorName{ get; set }
    Movie Movie{ get; set; }
    int MovieID{ get; set; }
 }

By convention EF will know that MovieID is the foreign key to Movie

Then change Actor code to this:

public class Actor
{
    int ID{get;set}
    string ActorName{ get; set; }
    Movie Movies{ get; set; }
}

Actors appear in many movies. Movies have many actors.... :-)

But going back to your one-to-many where an actor only appears in one movie - if you really want the foreign key to be Move_ID then add a data annotation:

[ForeignKey("Move_ID")]
Movie Movie{ get; set; }

Or configure it using FluentAPI

   modelBuilder.Entity<Actor>()
               .HasRequired(c => c.Movie)
               .WithMany(d => d.Actors)
               .HasForeignKey(c => c.Move_ID);
7
11/15/2013 1:54:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow