it is possible to be done using EF5?
X has many Y
Y has one X (one for many relationship)
however, Y has a second X that has no relation with the first X
is this 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; }
}
did 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's possible, but you need to tell EF that X.Ys and Y.X (and not Y.X2) belong together in a single one-to-many relationship, for example by using the InverseProperty attribute:
[ForeignKey("id_X")]
[InverseProperty("Ys")]
public X X { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With