1


读了几遍,明白我在正确提问方面不太擅长。对问题做了一些更正。

我的应用程序中有 2 个类:ContractorContractorGroup.

  1. 每个Contractor人都有一个父母Contractor。父母Contractor只能看到它的家属。并且看不到它的眷属的眷属。只有一层可见性。

  2. 父母Contractor可以将它的依赖分组ContractorsContractorGroup.

    因此,许多依赖Contractors于一个ContractorGroup(多对一)
    Contractor具有 NavProperty ContractorGroup,它所属的组。每个都Contractor可以是 ONLY IN ONE ContractorGroup

示例: 我是父母Contractor,有 5 个受抚养人Contractors,我想将其中的前 2 个分组为 1st ContractorGroup,最后 3 个分组为 2nd ContractorGroup。因此,要实施的选项:

首先:我不能包含将 2 个组中的每一个连接到 parentVisibleToContractorId-id of my parentContractor)。 在这种情况下,我可以进行类似于以下的查询:ContractorGroupContractor

    var ContractorGroupsToDispalayForParentContractor =
context.ContractorGroups.Where(p => p.Contractors.All(p => p.Parent == ParentContractor));

换句话说:“查找所有由具有 parent == ParentContractor 的承包商组成的组”
在此选项中,一切正常。DbSchema 简单明了。但我不喜欢这个查询。

第二:或者我可以引入 FK( VisibleToContractorId)。因此,一个父母Contractor有很多ContractorGroups由依赖组成的Contractors。然后我有一个更简单,更强大的查询:

    var ContractorGroupsToDispalayForParentContractor = 
context.ContractorGroups.Where(p => p.VisibleToContractor == ParentContractor);

我喜欢这个查询。但是 EF 引入了奇怪的 DbColumn ,它总是null。>:-E

短数据库架构:

Table("Contractor")
ContractorId = PK
ContractorGroupId = FK
ContractorGroup_ContractorGroupId = FK <--- This One

Table("ContratorGroup")
ContractorGroupId = PK
VisibleToContractorId = FK

我的域类和实体配置:

public class Contractor : IObjectWithState
{
    [Key]
    public virtual int ContractorId { get; set; }

    public virtual Contractor Parent { get; set; }
    public virtual int? ParentId { get; set; }

    public virtual ContractorGroup ContractorGroup { get; set; }
    public virtual int? ContractorGroupId { get; set; }

    public virtual ICollection<ContractorGroup> GroupsVisible { get; set; } 
 }

public class ContractorGroup : IObjectWithState
{
    [Key]
    public virtual int ContractorGroupId { get; set; }

    public virtual Contractor VisibleToContractor { get; set; }
    public virtual int? VisibleToContractorId { get; set; }

    public virtual ICollection<Contractor> Contractors { get; set; }            
}

实体配置(仅在 中ContractorGroupConfiguration):

HasMany(p => p.Contractors).WithOptional(p=>p.ContractorGroup);
HasOptional(p => p.VisibleToContractor).WithMany(
       p=>p.GroupsVisible).HasForeignKey(p=>p.VisibleToContractorId);

它是EF中的错误吗?您更喜欢领域模型的第一个第二个实现是什么?

谢谢。

4

1 回答 1

0

The point is that you need to tell EF that the associations ContractorGroup.VisibleToContractor and Contractor.GroupsVisible are no independent associations (with two FK fields), but are two parts of a bidirectional association. Replace the entity configurations by:

class ContractorConfiguration : EntityTypeConfiguration<Contractor>
{
    public ContractorConfiguration()
    {
        HasMany(c => c.GroupsVisible).WithOptional(g => g.VisibleToContractor);
    }
}

Without this, EF creates the field ContractorGroup_ContractorGroupId as a FK for Contractor.GroupsVisible on top of the FK VisibleToContractorId.

于 2012-11-11T09:40:59.170 回答