简体   繁体   English

Code First实体框架和外键

[英]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. 数据库首先使我能够从一个actor查询电影,但也允许我设置actor的forgien键属性来更新数据库。 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. 我不想获取Movie对象并设置属性,如果我知道我的电影的ID我宁愿只设置外键而没有调用来获取电影。

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. 我想使用codefirst和实体迁移,但我想要与数据库相同的能力首先在对象上设置外键。

Cheers for the help :-D 干杯的帮助:-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 按照惯例, EF将知道MovieIDMovie的外键

Then change Actor code to this: 然后将Actor代码更改为:

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 : 但回到你的一对多,其中演员只出现在一部电影中 - 如果你真的想要外键是Move_ID那么添加一个数据注释

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

Or configure it using FluentAPI 或者使用FluentAPI配置

   modelBuilder.Entity<Actor>()
               .HasRequired(c => c.Movie)
               .WithMany(d => d.Actors)
               .HasForeignKey(c => c.Move_ID);

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

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