Question

I'm new to Code First, and try to build my data model. All is ok, except one issue, i try to map next things:

public class Something
{
       ...
       public virtual Layer Layer1 { get; set; }
       public virtual Layer Layer2 { get; set; }
       public virtual Layer Layer3 { get; set; }
       ...
}

public class Layer
{
       ...
       public virtual Something Something { get; set; }
       ...
}

The Something class maps ok, but relation backwards from Layer to Something don't maps at all, in database table there are null, i try almost everything, for now i don't have any idea... Why Layer can't refer to Something?

Thanks in advance.

Was it helpful?

Solution

  1. You have three FK's, so you need three properties of type Layer in class Something, and also three properties of type Something in class Layer. You cannot somehow gather all related Something's in the Layer class in a single property.
  2. Since you have multiple FK's between two tables, you need to specify the id's, and connect the id's with the navigation properties using data annotations.
  3. I'm assuming 'normal' FK's, so that would mean that a Layer record could be referenced by multiple Something's. If that is the case, than the Something-properties in the Layer class would need to be collection.

Together, this results in:

public class Something {
        public int SomethingId { get; set; }
        [ForeignKey("Layer1")]
        public int Layer1Id { get; set; }
        [ForeignKey("Layer2")]
        public int Layer2Id { get; set; }
        [ForeignKey("Layer3")]
        public int Layer3Id { get; set; }
        [ForeignKey("Layer1Id")]
        public Layer Layer1 { get; set; }
        [ForeignKey("Layer2Id")]
        public Layer Layer2 { get; set; }
        [ForeignKey("Layer3Id")]
        public Layer Layer3 { get; set; }
    }

    public class Layer {
        public int LayerId { get; set; }
        [InverseProperty("Layer1")]
        public Something Something1 { get; set; }
        [InverseProperty("Layer2")]
        public Something Something2 { get; set; }
        [InverseProperty("Layer3")]
        public Something Something3 { get; set; }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top