1

Let's say I have database table A with optional property X. I have table B with a composite key (Y, X). These two tables are not explicitly related in any way.

e.g.

create table A
(
    Id uniqueidentifier not null,
    X uniqueidentifier null
)

create table B
(
    Y uniqueidentifier not null,
    X uniqueidentifier not null,
    Constraint PK_B Primary Key (Y, X)
)

A and B are implicitly related via property X, in the sense that X is an orphan id (its base table has been moved out)

For my model A in C# code, how can I populate IList<B> using property X to get all items in B containing X? Ideally, I'd like to use Fluent API configurations.

e.g

public class A {
    public Guid Id {get; set;}
    public Guid? X {get; set;}
    public IList<B> RelatedItems {get; set;}
}

public class B {
    public Guid X {get; set;}
    public Guid Y {get; set;}
}

How do I configure my entities using Fluent API so that I can use something like

var list = await context.AQuery()
.Include(a => a.RelatedItems)
.ToListAsync().ConfigureAwait(false);

or any other way to populate IList in A

Thanks in advance!

9
  • Hi have you tried something already? That we we can see where you are and if you actually already have the table with composite key. If you haven't than you should make that your main goal first.
    – Stefan
    Aug 19, 2018 at 16:12
  • Since X is not the PK of A, you can't let EF6 relate B to A. Hence the only options is to use LINQ queries with manual joins.
    – Ivan Stoev
    Aug 19, 2018 at 16:27
  • @Stefan - This is exactly what we have. The reason is, both the tables were having Foreign Key X referring to a table which we decided to remove on some performance concerns. But we still need to get the related records as I described. Previously it was easy via this removed table!!
    – raj02
    Aug 19, 2018 at 17:07
  • @IvanStoev - The manual way requires some back and forth between separate databases because of our removed (related) table in a separate database as I mentioned earlier. I was kind of trying to avoid that if there is some magic configuration!
    – raj02
    Aug 19, 2018 at 17:11
  • 1
    @GertArnold, IvanStoev Looks like there is only manual (LINQ) way left for me. Thanks all. Will update/share if I find something interesting.
    – raj02
    Aug 19, 2018 at 20:43

1 Answer 1

0

in ur model a x is a property , a property has a getter , u can set the get method of the x property to retrieve the records from the database (similar to the lazy loading design pattern )

public IList<SomeStuff> X {
get { // go get records from database }
}

this will cost u an extra so i am not sure if this is what u want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.