如何使用现有关系基于它创建多个导航属性?

时间:2012-11-20 16:10:29

标签: c# entity-framework ado.net entity-framework-4.1

我有两张桌子,比如说:

老师1 ------- * Pupil

我只有一个名为'Pupils'的导航属性。

仅举这个例子,我想做的是创建两个名为'Boys'的导航属性,另一个名为'Girls',它将基于一个名为'IsMale'的bool。

我已从数据库生成实体模型,因此这不是代码优先的。

谁能告诉我怎么做?我是否需要修改生成的源?如果是这样,如果发生更新会发生什么,我会丢失代码吗?

谢谢你的时间!

克雷格

这是我的解决方案:

添加导航属性,然后在属性中选择教师和学生之间的关联。

在生成的代码中,找到导航属性'Boys',添加一个.where到最后将选择男孩,如:

    [XmlIgnoreAttribute()]
    [SoapIgnoreAttribute()]
    [DataMemberAttribute()]
    [EdmRelationshipNavigationPropertyAttribute("SchoolModel", "FK_Pupils_Teacher", "Pupil")]
    public EntityCollection<Pupil> Boys
    {
        get
        {
            return (EntityCollection<PriceKey>)((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<PriceKey>("SchoolModel.FK_Pupils_Teacher", "Pupil").Where(p => p.IsMale == true);
        }
        set
        {
            if ((value != null))
            {
                ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Pupil>("SchoolModel.FK_Pupils_Teacher", "Pupil", value);
            }
        }
    }

这是我的解决方案。所以现在我可以使用导航属性并将传回我想要的内容。

我也喜欢下面的答案!并认为一个是更好的主意:))

干杯!

1 个答案:

答案 0 :(得分:1)

Teacher.cs文件放在.EDMX文件所在的文件夹中:

partial class Teacher
{
    public IEnumerable<Pupil> Boys
    {
        get { return Pupils.Where(x => x.IsMale); }
    }

    public IEnumerable<Pupil> Girls
    {
        get { return Pupils.Where(x => !x.IsMale); }
    }
}

顺便说一句,这些不是导航属性。我认为你不能那样做。