0

I would like to define an entity relationship with fluent api like this:

SELECT * 
FROM tableA a
JOIN tableB b on a.itemId = ISNULL(b.idX, b.idY)

Is it even possible?

This code snippet:

modelBuilder.Entity<TableAEntity>()
            .HasOne(i => i.TableBEntity)
            .WithOne()
            .HasForeignKey<TableAEntity>(i => i.IdX ?? i.IdY)...

produces an error:

ArgumentException: The properties expression 'i => (i.IdX ?? i.IdY)' is not valid.
The expression should represent a property access: 't => t.MyProperty'.
When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression

EDIT: The DB model:

[Table("tableA")]
class TableAEntity 
{
  public [Column("idX")] public string IdX { get; set; }
  public [Column("idY")] public string IdY { get; set; }
  public TableBEntity TableBEntity { get; set; }
}

[Table("tableB")]
class TableBEntity 
{
  [Key]
  public int Id { get; set; }
}

Thank you

myro
  • 1,158
  • 2
  • 25
  • 44

1 Answers1

2

Yes, it is possible.

Parent class must have a collection of child items...

public class Parent
{
    public int ParentId { get; set; }

    ...

    public virtual ICollection<Child> Childs{ get; set; }
}

And Child class a referent to the Parent and to its ID (note, virtual keyword is important)

public class Child
{
    public int ChildId{ get; set; }

    ...

    public int ParentId { get; set; }
    public virtual Parent Parent{ get; set; }
}

And the fluent would be like:

public class ParentChildContext : DbContext
{
    public DbSet<Parent> Parents{ get; set; }
    public DbSet<Child> Childs{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // configures one-to-many relationship
        modelBuilder.Entity<Child>()
            .HasRequired<Parent>(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey<int>(c => c.ParentId);          }
    }
}

I hope it helps,

Juan

Note: take a look at these links, might help you bit more:

http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx

https://msdn.microsoft.com/en-us/library/jj591620(v=vs.113).aspx

Implementing Zero Or One to Zero Or One relationship in EF Code first by Fluent API

Juan
  • 2,156
  • 18
  • 26
  • Sorry, my I named the properties confusingle parent/child. They are just IDs that map the same table. The IdX is never NULL, but if IdY is not null I want the TableBEntity be mapped by idY. I have edited the question. – myro Sep 29 '17 at 07:18
  • Then what you are using, your entity, is a tree, take a look at this to see if helps: https://stackoverflow.com/questions/35554821/ef-fluent-api-for-hierarchical-data – Juan Sep 29 '17 at 07:40