My example is like the following: I've a [Table1] which has one-to-many relation to [Table2].
Let say it looks like:
[Table1]:
[Id] int
[Table2]:
[Table1Id] int (foreign key to [Table1])
[UniqueColumnAtTable2ForGivenTable1Id] int
[Table2] has indeed foreign key to [Table1], and it's possible to have multiple elements in [Table2], that has relation to [Table1].
I know how to define mapping between [Table1] and [Table2] from code, means:
public class Table1
{
public int Id { get; set; }
public virtual ICollection<Table2> Table2Objects { get; set; }
}
public class Table1_Mapping : EntityTypeConfiguration<Table1>
{
public class Table1()
{
this.HasKey(x => x.Id);
this.HasMany(x => x.Table2Objects).WithOptional().HasForeignKey(x => x.Table1);
}
}
But is there a way to define Entity framework mapping, where I would specify One-to-many mapping, but only with mapping to one specific row from [Table2]? I do have [UniqueColumnAtTable2ForGivenTable1Id] column at [Table2] which is always unique for given [Table1] - therefore I know, that running something like:
SELECT * FROM [Table2] WHERE [Table1Id] = 123 AND [UniqueColumnAtTable2ForGivenTable1Id] = 456
will always result with one row queried.
From C# code what I need, is something like:
public class Table1
{
public int Id { get; set; }
public virtual ICollection<Table2> Table2Objects { get; set; }
public virtual Table2 Table2Object456 { get; set; }
}
public class Table1_Mapping : EntityTypeConfiguration<Table1>
{
public class Table1()
{
this.HasKey(x => x.Id);
this.HasMany(x => x.Table2Objects).WithOptional().HasForeignKey(x => x.Table1);
this.MagicMethod(x => x.Table2Object456).WithOptional().HasForeignKey(x => x.Table1).OtherMagicMethodWhichAllowsToPutFilter(x => x.UniqueColumnAtTable2ForGivenTable1Id == 456);
}
}
Of course this fragment is what I need:
this.MagicMethod(x => x.Table2Object456).WithOptional().HasForeignKey(x => x.Table1).OtherMagicMethodWhichAllowsToPutFilter(x => x.UniqueColumnAtTable2ForGivenTable1Id == 456);
MagicMethod
method? I am not familiar with it.using Magic;
in the beginning of your file? :)