Reputation: 403
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?
Upvotes: 0
Views: 107
Reputation: 397
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.
Upvotes: 0
Reputation: 13488
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);
Upvotes: 2