使用EF Code First查找表

时间:2014-12-30 09:41:35

标签: entity-framework ef-code-first

我想用EF Code First创建Resource and RelatedResources表,如下所示:

Table Resource
int Id
string ResourceName
int Category

Table RelatedResource
int ResourceId
int RelatedResourceId

我尝试如下,但是  错误:类型为“Models.ResourceRelated”的属性“ResourceId”上的ForeignKeyAttribute无效。在依赖类型“Models.ResourceRelated”上找不到导航属性“Resource”。 Name值应该是有效的导航属性名称。

public class ResourceRelated
    {
        [ForeignKey("Resource")]
        public int ResourceId { get; set; }
        public virtual Resource Resoure { get; set; }
        public virtual ICollection<Resource> RelatedResource { get; set; }
    }

请咨询!

1 个答案:

答案 0 :(得分:0)

如果你想要RelatedResource表,那么你需要多对多的关系。你可以通过下一步实现这个目标

public class Resource
{
    public int ResourceId { get; set; }
    public string ResourceName { get; set; }
    public int Category { get; set; }

    [InverseProperty("Resoure")]
    public virtual ICollection<RelatedResource> RelatedResource { get; set; }
    [InverseProperty("ResourceRelated")]
    public virtual ICollection<RelatedResource> ResourceRelated { get; set; }
}

public class RelatedResource
{
    [Key]
    [Column(Order = 1)]
    [ForeignKey("Resoure")]
    public int ResourceId { get; set; }
    [Key]
    [Column(Order = 2)]
    [ForeignKey("ResourceRelated")]
    public int ResourceRelatedId { get; set; }

    public virtual Resource Resoure { get; set; }
    public virtual Resource ResourceRelated { get; set; }
}

如果您不希望在代码中使用RelatedResource,那么您可以使用

public class Resource
{
    public int ResourceId { get; set; }
    public string ResourceName { get; set; }
    public int Category { get; set; }
    public virtual ICollection<Resource> RelatedResource { get; set; }
    public virtual ICollection<Resource> ResourceRelated { get; set; }
}

您需要下一个额外配置

internal class ResourceConfiguration : EntityTypeConfiguration<Resource>
{
    public ResourceConfiguration()
    {
        HasMany(s => s.ResourceRelated).WithMany(c => c.RelatedResource)
            .Map(cs => { 
                cs.MapLeftKey("ResourceId"); 
                cs.MapRightKey("RelatedResourceId");
                cs.ToTable("RelatedResource"); }
            );
    }
}

最后添加此配置

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    ///other configuration code
    modelBuilder.Configurations.Add(new ResourceConfiguration());
}

但是如果你想拥有&#34;资源树&#34;比你不需要RelatedResource表

public class Resource
{
    public int ResourceId { get; set; }
    public string ResourceName { get; set; }
    public int Category { get; set; }
    public int? ResourceRelatedId { get; set; }

    public Resource ResourceRelated { get; set; }
    [ForeignKey("ResourceRelatedId")]
    public virtual ICollection<Resource> RelatedResource { get; set; }
}