简体   繁体   English

在Entity Framework 6.2中获取每个相关实体

[英]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. 我有一个在其他实体中使用的Service实体。 I want to get all entities that use Service . 我想获取所有使用Service实体。

What I mean is get a list of entities that use Service like this: 我的意思是获取使用Service的实体的列表,如下所示:

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: 近似代码,其中Assembly.GetExecutingAssembly()可以用适当的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. 添加导航ServiceId并使用它。 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: 然后从另一端查询EF:

_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. 一级继承在EF中是可行的,但要当心,如果您过度使用它,可能会变得凌乱。 The problem with not having them connected this way is not too bad, you only have to ask for each entity separatly. 没有通过这种方式连接它们的问题还算不错,您只需要分开请求每个实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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