简体   繁体   中英

Entity Framework query with simple join

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM