简体   繁体   中英

Code First entity framework and foreign keys

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

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

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