开发者

Combining 2 IQueryable results

I found some questions that looked similar, but not exactly the sa开发者_Go百科me 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?


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜