使用自定义键名映射泛型Many-Many

问题描述 投票:0回答:1
public class Entity1
{
    public int Id { get; set; }
    public Guid EntityKey { get; set; }
    public ICollection<Entity2> Entity2s { get; set; }
}

public class Entity2
{
    public int Id { get; set; }
    public Guid EntityKey { get; set; }
}

public class EntityMapping 
{
    public int Id { get; set; }
    public Guid ParentKey { get; set; }
    public EntityType ParentType { get; set; }
    public Guid ChildKey { get; set; }
    public EntityType ChildType { get; set; }
}

我需要使用流畅的配置API执行以下操作:

select e2.* from Entity1 e1
join Entitymapping em on em.ParentKey == e1.EntityKey && em.ParentType == 'Entity1'
join Entity2 e2 on em.ChildKey == e2.EntityKey

我打电话的时候:entity1.Entity2s.ToList()

只有EF 4中的流畅配置才能实现这一点吗?

c# entity-framework entity-framework-4
1个回答
-2
投票

好的,首先。为什么不使用Id字段作为主要字段?由SQL Server维护为唯一等等。每个实体有两个密钥要求麻烦。

与我给here几乎相同的M-M答案

你的实体需要一些工作。 Entity1 / Entity2导航属性应指向List <EntityMapping>,EntityMapping应指向Entity1和Entity2中的每一个。它是1-1的连接表,其中每一方都可以很多,因此是多对多的。如果您希望所有Entity1及其关联的Entity2更像是这样:

。DbSet.Entity1.Include( “EntityMapping”)的实例包括( “EntityMapping.Entity2”)ToList();

使用单个表来存储许多不同实体之间的关系,这些实体仍然可以使用类似的结构。将会有一些“幕后”检查,以强制执行1-1或1-M关系进入M-M模具,打赌这应该让你开始......

public class Entity1
{
    public int Id { get; set; }
    public Guid EntityKey { get; set; }
    public EntityType E1Type { get; set; }
    public ICollection<EntityMapping> Entity2s { get; set; }
}

public class Entity2
{
    public int Id { get; set; }
    public Guid EntityKey { get; set; }
    public EntityType E2Type { get; set; }
    public ICollection<EntityMapping> Entity1s { get; set; }
}

public class EntityMapping 
{
    public int Id { get; set; }
    public int ParentKey { get; set; }
    public int ChildKey { get; set; }
    public Entity1 Entity1 { get; set; }
    public Entity2 Entity2 { get; set; }
}

对于所有称为“Foo”和“Bar”子实体的实体(假设Foo也可能与“Widgets”相关)有一种EF“方式”可以做到这一点,但您正在拍摄的SQL SELECT是

select e1.EntityKey as e1Key, e2.EntityKey as e2Key from Entity1 e1
inner join EntityMapping e3 on e3.ParentKey = e1.Id
inner join Entity2 e2 on e2.Id = e3.ChildKey
where e1.E1Type = "Foo" and e2.E2Type = "Bar"

EF-说话

var temp = DbSet.Entity1.Select(p => p.E1Type == "Foo").Include("EntityMapping").Include("EntityMapping.Entity2");
var result = temp.Where(r => r.E2Type == "Bar").ToList();

可能会结合这些,但我必须修补而不是“关闭袖口”。那更好?

© www.soinside.com 2019 - 2024. All rights reserved.