两个属性

时间:2017-09-11 09:50:40

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

我想将一个属性用作两个单独实体的外键 - 一次作为复合外键的一部分,一次作为单个外键。这是我的意思的一个简单例子:

public class ParentEntity{
    [Key, Column(Order = 1)]
    String Id {get; set;}
    [Key, Column(Order = 2), ForeignKey("Year")]
    int YearId {get; set;}

    [ForeignKey("YearId")]
    Year Year;
    virtual ICollection<ChildEntity> Children {get; set;}
}

public class ChildEntity{
    [Key, Column(Order = 0), ForeignKey("Parent")]
    String Id {get; set;}
    [Key, Column(Order = 1), ForeignKey("Parent")]
    String ParentId {get; set;}
    [Key, Column(Order = 2), ForeignKey("Parent, Year")]
    int YearId {get; set;}

    [ForeignKey("ParentId, YearId")]
    ParentEntity Parent{get; set;}

    [ForeignKey("YearId")]
    Year Year {get; set;}
}

public class Year{
    [Key]
    int YearId {get; set;}
}

ChildEntity中的YearId / Year属性既可以作为主键(ParentId / Year)到ParentEntity的一部分,也可以作为Year表的外键。 / p>

但是,标记ForeignKey("Parent, Year")无效,因为它只能将一个参数带到导航属性。这是我收到的错误消息:

Additional information: The ForeignKeyAttribute on property 'YearId' on type 'CodeFirst.Models.ChildEntity' is not valid. 
The navigation property 'Parent, Year' was not found on the dependent type 'CodeFirst.Models.ChildEntity'. 
The Name value should be a valid navigation property name.

我认为这是有意义的,它正在寻找一个名为“Parent,Year”的导航属性,而不是两个导航属性,名为“Parent”和“Year”。

如何强制EntityFramework / CodeFirst正确识别此模式?

注意:我将实体命名为“父”/“子”,但它们之间没有继承关系(实际上是所有权关系)。

2 个答案:

答案 0 :(得分:0)

您只需要导航属性上的ForeignKeyAttribute或外键属性。不是都。像这样:

    public class ParentEntity
    {
        [Key, Column(Order = 1)]
        public String Id { get; set; }
        [Key, Column(Order = 2)]
        public int YearId { get; set; }

        [ForeignKey("YearId")]
        Year Year;
        public virtual ICollection<ChildEntity> Children { get; set; }
    }

    public class ChildEntity
    {
        [Key, Column(Order = 0)]
        public String Id { get; set; }
        [Key, Column(Order = 1)]
        public String ParentId { get; set; }
        [Key, Column(Order = 2)]
        public int YearId { get; set; }

        [ForeignKey("ParentId, YearId")]
        public ParentEntity Parent { get; set; }

        [ForeignKey("YearId")]
        public Year Year { get; set; }
    }

    public class Year
    {
        [Key]
        public int YearId { get; set; }
    }

答案 1 :(得分:0)

public class ParentEntity{
    [Key, Column(Order = 1)]
    String Id {get; set;}
    [Column(Order = 2)]
    int YearId {get; set;}

    [ForeignKey("YearId")]
    virtual Year Year;
    virtual ICollection<ChildEntity> Children {get; set;}
}

public class ChildEntity{
    [Key, Column(Order = 0)]
    String Id {get; set;} 
    String ParentId {get; set;}
    int YearId {get; set;}
    [ForeignKey("ParentId")]
    virtual ParentEntity Parent{get; set;}
    [ForeignKey("YearId")]
    virtual Year Year {get; set;}
}

public class Year{
    [Key]
    int YearId {get; set;}
}