I have a problem regarding navigational properties of many-to-many relations.
As I read on MSDN, there is an option to define a ForeignKey
property to a navigational property. Now I want to use this feauture for many-to-many relation but I can't get it to work.
I am using EF 6.1.3.
My classes:
public class Class1
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[ForeignKey(nameof(Class2s))]
public ICollection<Guid> Class2Ids { get; set; }
[ForeignKey(nameof(Class2Ids))]
public ICollection<Class2> Class2s { get; set; }
[ForeignKey(nameof(Class3))]
public Guid Class3Id { get; set; }
public Guid Class3 { get; set; }
}
public class Class2
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[ForeignKey(nameof(Class1s))]
public ICollection<Guid> Class1Ids { get; set; }
[ForeignKey(nameof(Class1Ids))]
public ICollection<Class1> Class1s { get; set; }
}
public class Class3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
}
The problem that the navigational property get loaded but the id collection stays empty.
public static void Main(string[] args)
{
using (SomeContext context = new SomeContext())
{
var classes = context.Classe1Set
.Include(c => c.Class2s)
.Include(c => c.Class2s)
.First();
classes.Class3; // filled with correct object
classes.Class3Id; // filled with correct guid
classes.Class2s; // is filled with 2 elements
classes.Class2Ids; // problem: is Empty List
}
}
What am I doing wrong?
Edit: Updated the classes to represent the problem better. The many-to-many connection is created correctly on the DB side. The problem is just the property Class1Ids not filling correctly whereas Class3Id does.
Thanks for any help.