carlsb3rg
carlsb3rg

Reputation: 772

Combining 2 IQueryable results

I found some questions that looked similar, but not exactly the same so I'll go for it.

I'm using EF to retrieve 2 tables. These tables/entities have no real "is a" relationship. They just happen to have a couple of common fields which I want to expose in a list containing the first N entries of a combination between the two tables. Each row has to have some way of identifying which type it is and which instance it points to.

I have solved the problem, but I guess I was wondering if there was a better way. My solution was to create a ViewModel class:

intenal class EntityAEntityBCombination
{
    public int? EntityAID { get; set; }
    public int? EntityBID { get; set; }
    public string CommonProperty { get; set; }
}

Then I did this:

var results = (
    from a in EntityAList select new EntityAEntityBCombination
        { EntityAID = a.Id, EntityBID = null, CommonProperty = a.CommonProperty }
    ).Concat(
    from b in EntityBList select new EntityAEntityBCombination
        { EntityAID = null, EntitiyBID = b.Id, CommonProperty = b.CommonProperty }
    ).Fetch(N)

It works, but seems dirty. Any suggestions?

Upvotes: 1

Views: 190

Answers (1)

Bazzz
Bazzz

Reputation: 26922

Have a look at this, perhaps it doesn't work straight out of the box, but it should give you an idea:

public class EntityA : IEntity
{}

public class EntityB : IEntity
{}

List<IEntity> results = 
(from a in EntityAList select a).Cast<IEntity>()
.Concat(
(from b in EntityBList select b).Cast<IEntity>()
)
.Fetch(N).ToList();

foreach (IEntity entity in results)
{
 if (entity is EntityA)
  // do something with entity A

 if (entity is EntityB)
  // do something with entity B
}

Upvotes: 2

Related Questions