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属性为外键属性指定不同的名称。

  • 相关阅读:
    常用的40个建站代码及使用说明
    vs2008与vs2005的冲突
    ASP调用.net的webservices的实现方法
    Web Development Tools for the Power Developer
    XML Web Service开发实例——通过Windows Forms调用Web Service
    “家贼”倒卖“征途”源代码 13万元卖给识货人
    [轉載]让UpdatePanel支持文件上传
    DB2与Sybase/Oracle/Informix的比较
    網頁打印代碼大全
    完整的网站间共享数据的WebService
  • 原文地址:https://www.cnblogs.com/talentzemin/p/7218374.html
Copyright © 2011-2022 走看看