Code First 数据注释--InverseProperty 和 ForeignKey

ForeignKey

按照约定在Post类中看到BlogId属性,会认为是Blog类的外键,但是在Blog类中并没有BlogId属性,解决方法是,在 Post 中创建一个导航属性,并使用 Foreign DataAnnotation 来帮助 Code First 了解如何在两个类之间创建关系(那就是使用 Post.BlogId 属性)以及如何在数据库中指定约束。

public class Post 
{ 
        public int Id { get; set; } 
        public string Title { get; set; } 
        public DateTime DateCreated { get; set; } 
        public string Content { get; set; } 
        public int BlogId { get; set; } 
        [ForeignKey("BlogId")] 
        public Blog Blog { get; set; } 
        public ICollection<Comment> Comments { get; set; } 
}

设置了ForeignKey的情况:

没设置的情况:

InverseProperty

当类之间存在多个关系时,将使用InverseProperty

在 Post 类中,可能需要跟踪是谁撰写了博客文章以及谁编辑了它。下面是 Post 类的两个新的导航属性。

public Person CreatedBy { get; set; } 
public Person UpdatedBy { get; set; }

还需要在这些属性引用的 Person 类中添加内容。Person 类具有返回到 Post 的导航属性,一个属性指向该用户撰写的所有文章,一个属性指向该用户更新的所有文章。

public class Person 
{ 
        public int Id { get; set; } 
        public string Name { get; set; } 
        public List<Post> PostsWritten { get; set; } 
        public List<Post> PostsUpdated { get; set; } 
}

设置了InverseProperty

未设置InverseProperty

原文地址:https://www.cnblogs.com/goodlucklzq/p/4538500.html