简体   繁体   中英

Getting every related entity in Entity Framework 6.2

public class Service
{
    public int Id { get; set; }
    public string Title { get; set; }
}

public class Store
{
    public int Id { get; set; }
    public virtual Service Service { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public virtual Service Service { get; set; }
}

public class Operation
{
    public int Id { get; set; }
    public virtual Service Service { get; set; }
}

I have a Service entity which is used in other entities. I want to get all entities that use Service .

What I mean is get a list of entities that use Service like this:

public virtual Service Service { get; set; }

Is this possible in Entity Framework?

You can do it via reflection. Approximate code, where Assembly.GetExecutingAssembly() can be replaced with appropriate Assembly/Assemblies:

var types = Assembly.GetExecutingAssembly().GetTypes()
            .Where(x => x.GetProperties().Any(y => y.PropertyType == typeof(Service)))
            .ToList();

(instance.GetType().GetProperties().Where(y => y.PropertyType == typeof(DbSet<Service>))
.First().GetValue(instance) as DbSet<Service>).Add(newItem);

Add navigational ServiceId and use that. You are probably showing a simplification of your code but I would do something like this:

public class Service
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<ObjectUsingService> MyServiceUsers {get; set;
}

public ObjectUsingService
{
    public int? ServiceId {get; set;}
    public virtual Service Service { get; set; }
}

public class Store : ObjectUsingService
{
    public int Id { get; set; }
}

//...

And then query EF from the other end:

_context.Services.Include(s => s.MyServiceUsers).Where(s => s.MyServiceUsers.Any())

One level of inheritance is doable in EF but be wary, it might get messy if you overuse it. The problem with not having them connected this way is not too bad, you only have to ask for each entity separatly.

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