1

I am using Entity Framework 6 in a project and am having trouble creating a query.

Say my classes are defined like:

public class MyContext : DbContext
{
    public MyContext(string connectionString) : base(connectionString)
    {
    }

    public DbSet<EntityXXX> XXXSet { get; set; }
    public DbSet<EntityYYY> YYYSet { get; set; }
}


public class EntityXXX
{
    public string XXXName { get; set; }
    public int id { get; set; }
    public int YYYid { get; set; }
}

public class EntityYYY
{
    public string YYYName { get; set; }
    public int id { get; set; }
}

The YYYid property of EntityXXX is the 'id' of the EntityYYY instance that it relates to.

I want to be able to fill a Grid with rows where the first Column is XXXName and the second column is YYYName (from its related EntityYYY), but I can't see how to do this?

I'm sure it's really simple, but I'm new to EF.

1 Answer 1

2

You need to put a virtual navigation property on your EntityXXX

public virtual EntityYYY YYY { get; set; }

Then you can do a projection:

db.XXXSet
    .Select(x => new { x.XXXName, YYYName = x.YYY.YYYName })
    .ToList();

Which will get you the list you need.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks for your reply. I'm a bit confused why your solution doesn't refer to the id's at all? Can you explain please? I thought they would be involved somehow to make the match?
As long as you have it configured correctly, it knows that YYYid is the foreign key to the YYY table, thus the YYY property is the row from YYY that foreign key refers to. It's using the id in the background. If you were to look at the SQL produced it'd have a JOIN to the YYY table on the foreign key.
Appreciate the additional comments - Thank you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.