外键关联是除了对应的导航属性之外,模型中还具有外键属性的位置。独立关联是指您的数据库中有一个外键列,但与该列相对应的外键属性不在您的模型中-即,您具有NavigationProperty,但是没有外键属性可以告诉您该ID的ID值是多少。相关财产实际上并没有转到相关财产。
这是带有独立关联的模型的示例(请注意,从属没有外键-只是导航属性):
public class Dependent{ public int Id { get; set; } [Required] public Principal PrincipalEntity { get; set; }}public class Principal{ public int Id { get; set; } public ICollection<Dependent> DependentEntities { get; set; }}public class MyContext : DbContext{ public DbSet<Dependent> Dependents { get; set; } public DbSet<Principal> Principals { get; set; }}这是具有外键关联的相同模型的示例(请注意PrincipalEntity_Id属性和[ForeignKey()]属性):
public class Dependent{ public int Id { get; set; } public int PrincipalEntity_Id { get; set; } [Required] [ForeignKey("PrincipalEntity_Id")] public Principal PrincipalEntity { get; set; }}public class Principal{ public int Id { get; set; } public ICollection<Dependent> DependentEntities { get; set; }}public class MyContext : DbContext{ public DbSet<Dependent> Dependents { get; set; } public DbSet<Principal> Principals { get; set; }}请注意,您的数据库不会更改-基础数据库始终具有外键列,但是具有独立关联却未公开。
使用外键关联,您只需更改外键的值即可更新关系。如果您知道该值,则这很方便,因为您不需要加载要将导航属性更新到的实体。


![什么是独立协会和外键协会?[重复] 什么是独立协会和外键协会?[重复]](http://www.mshxw.com/aiimages/31/433041.png)
