zoukankan      html  css  js  c++  java
  • 转 Code First 数据注释--InverseProperty 和 ForeignKey

    转自https://www.cnblogs.com/goodlucklzq/p/4538500.html

    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

     
     
    个人理解:
    每个导航属性需要一个外键属性来确认两个表之间的关系,正常情况下,如果字段按照 "<导航属性名称><主体主键属性名称>"、"<主体类名称><primary key 属性名称>" 或 "<主体主键属性名称>"约定命名,那么这个字段将会被认为是外键。但是如果没有按照这个约定命名,又需要指定该字段为外键就需要用到ForeignKey,
     比如文中在导航属性上使用批注[ForeignKey("BlogId")] 的意思是将字段BlogId作为外键,并和该导航属性对应。
     
    如果一个从属表中只有一个导航属性,导航属性会使用表中仅有的一个外键对应,但是如果有两个导航属性,Code-First并不知道导航属性对应的外键是哪个,所以需要结合ForeignKey和InverseProperty使用
     
     
  • 相关阅读:
    Spring Cloud入门
    HTML常用标签
    Spring boot 入门
    数据库 基本操作
    jquery中的ajax方法参数
    反射详解
    SpringMVC框架
    Java NIO
    MQ(消息队列)的使用场景以及常见的MQ
    英文字母和中文汉字在不同字符集编码下的字节数
  • 原文地址:https://www.cnblogs.com/lidaying5/p/13060408.html
Copyright © 2011-2022 走看看