zoukankan      html  css  js  c++  java
  • 【译】第18节---数据注解-ForeignKey

    原文:http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

    ForeignKey属性可以应用于类的属性。对于ForeignKey关系, 默认Code First约定期望外键属性名与主键属性相匹配。

    看以下示例:

    public class Student
    {
        public Student()
        { 
            
        }
        public int StudentID { get; set; }
        public string StudentName { get; set; }
            
        //Foreign key for Standard
        public int StandardId { get; set; }
    
        public Standard Standard { get; set; }
    }
    
    public class Standard
    {
        public Standard()
        { 
            
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        
        public ICollection<Student> Students { get; set; }
       
        }

    正如你在上面的代码中可以看到的,Student类包括外键StandardId,它是Standard类中的主键属性。 所以现在,Code First将在Students类中创建StandardId列,如下所示:

    ForeignKey属性覆盖此约定。 你可以具有与依赖类的主键不同的外键属性名称。

    public class Student
    {
        public Student()
        { 
            
        }
        public int StudentID { get; set; }
        public string StudentName { get; set; }
            
        //Foreign key for Standard
        public int StandardRefId { get; set; }
    
        [ForeignKey("StandardRefId")]
        public Standard Standard { get; set; }
    }
    
    public class Standard
    {
        public Standard()
        { 
            
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        
        public ICollection<Student> Students { get; set; }
       
    }

    如上例所示,Student类包括StandardRefId外键属性名称而不是StandardId。 我们使用标准导航属性中的ForeignKey属性指定它,以便Code-First将将StandardRefId视为外键,如下所示:

    ForeignKey属性可以应用于key属性来指定它指向哪个导航属性,如下所示:

    public class Student
    {
        public Student()
        { 
            
        }
        public int StudentID { get; set; }
        public string StudentName { get; set; }
            
        //Foreign key for Standard
        
        [ForeignKey("Standard")]
        public int StandardRefId { get; set; }
    
        public Standard Standard { get; set; }
    }
    
    public class Standard
    {
        public Standard()
        { 
            
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        
        public ICollection<Student> Students { get; set; }
       
    }

    因此,你可以使用ForeignKey属性为外键属性指定不同的名称。

  • 相关阅读:
    Maven 集成Tomcat插件
    dubbo 序列化 问题 属性值 丢失 ArrayList 解决
    docker 中安装 FastDFS 总结
    docker 从容器中拷文件到宿主机器中
    db2 相关命令
    Webphere WAS 启动
    CKEDITOR 4.6.X 版本 插件 弹出对话框 Dialog中 表格 Table 自定义样式Style 问题
    SpringMVC JSONP JSON支持
    CKEDITOR 3.4.2中 按钮事件中 动态改变图标和title 获取按钮
    git回退到远程某个版本
  • 原文地址:https://www.cnblogs.com/talentzemin/p/7218374.html
Copyright © 2011-2022 走看看