EF5 one-to-many relationship
can be done with EF5?
X
has many Y
Y
has one X
(one for many relationships)
however Y
has a second X
which is not related to the firstX
Is it possible?
public class X
{
public int Id { get; set; }
public List<Y> Ys { get; set; }
}
public class Y
{
public int Id { get; set; }
public int id_X { get; set; }
[ForeignKey("id_X")]
public X X { get; set; }
public int id_X2 { get; set; }
[ForeignKey("id_X2")]
public X X2 { get; set; }
}
does not work.
The code looked like this.
class Program
{
static void Main(string[] args)
{
using (var context = new context())
{
var x = context.X.FirstOrDefault();
}
}
}
public class context : DbContext
{
public context()
: base(@"server=localhost\ALTAIRNOTESTI; uid=sa; pwd=13509; database=DDD")
{
}
public DbSet<X> X { get; set; }
public DbSet<Y> Y { get; set; }
}
public class X
{
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public List<Y> Ys { get; set; }
}
public class Y
{
[Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int id_X { get; set; }
[ForeignKey("id_X")]
[InverseProperty("Ys")]
public X X { get; set; }
public int id_X2 { get; set; }
[ForeignKey("id_X2")]
public X X2 { get; set; }
}
Yes it is possible, but you need to tell EF that X.Ys
and Y.X
(not Y.X2
) belong to each other in one one-to-many relationship, for example using the attributeInverseProperty
[ForeignKey("id_X")]
[InverseProperty("Ys")]
public X X { get; set; }