【问题标题】:Foreign key relationship外键关系
【发布时间】:2015-02-27 17:15:50
【问题描述】:

我正在尝试使用以下两个类设置外键。 我想使用 pAcqType 作为枚举并将类型的名称存储在另一个表中。我应该如何设置我的课程来做到这一点?

public class Property
{
    [Key]
    public int pID { get; set; }
    public string pAddress { get; set; }
    public string pCounty { get; set; }
    public string pCity { get; set; }
    public string pState { get; set; }
    public string pzip { get; set; }
    public virtual PropertyAcquisitionType pAcqType { get; set; }    <-- foreign key      
}

public class PropertyAcquisitionType
{
    [Key]        
    public int patID { get; set; }        
    public string patName { get; set; }
}

更新

丹让我思考。我尝试了以下方法,它似乎已经解决了。 它像我想要的那样在桌子上设置了外键。它甚至没有要求另一张桌子上的倒数。

    public int? pAcqType { get; set; }
    [ForeignKey("pAcqType")]
    public PropertyAcquisitionType patID { get; set; }

【问题讨论】:

    标签: asp.net entity-framework ef-code-first


    【解决方案1】:

    是否需要外键(数据库中的NOT NULL)?

    public int pAcqTypeId { get; set; }
    [ForeignKey("pAcqTypeId")]
    public virtual PropertyAcquisitionType pAcqType { get; set; }
    

    否则,

    public int? pAcqTypeId { get; set; }
    [ForeignKey("pAcqTypeId")]
    public virtual PropertyAcquisitionType pAcqType { get; set; }
    

    然后在你的其他类中,添加一个反比关系:

    public class PropertyAcquisitionType
    {
        [Key]        
        public int patID { get; set; }        
        public string patName { get; set; }
        [InverseProperty("pAcqType")]
        public virtual ICollection<Property> pOfThisType { get; set; }
    }
    

    这是使用 fluent API 定义关系的一种方法(实体类中没有属性)。请注意,使用此方法时,您不需要在 PropertyAcquisitionType 实体上添加 properties 属性来满足关系的反面,因为 .WithMany() 告诉 EF 它需要知道什么:

    public class MyDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Property>()
                .HasKey(x => x.pID)
                .HasRequired(x => x.pAcqType) // or HasOptional if using int?
                .WithMany() // or WithMany(x => x.pOfThisType) if you want to add / keep the inverse property
                .HasForeignKey(x => x.pAcqTypeId)
            ;
        }
    }
    

    【讨论】:

    • 无法确定类型“hoahelp.Models.PropertyAcquisitionType”和“hoahelp.Models.Property”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。
    • 它很挑剔。类型“hoahelp.Models.Property”的属性“pAcqType”上的 ForeignKeyAttribute 无效。在依赖类型“hoahelp.Models.Property”上找不到外键名称“PropertyAcquisitionTypeId”。 Name 值应该是一个逗号分隔的外键属性名称列表。
    • @Prescient 您将属性命名为PropertyAcquisitionTypeId,还是将其命名为pAcqTypeId?字符串中的值必须与类中的属性名称相匹配。如果你把它命名为pAcqTypeId,那么你应该使用[ForeignKey("pAcqTypeId")]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多