2

我需要 id 从我的父母那里获取数据集合。计划是使用 ParentId 从存储库中获取所有朋友。

为了说明我有一个 Parent 和 Child 类,还有一个 Mapper。我想我必须在 ParentMapper 中定义键。

请参阅我的代码中的评论

    {
        public class Child {
            public int IdChild { get; set; }
            public string ChildName {get;set;}
            // here is the problem
            //I need to define ParentID as ForeignKey in some way but how??
            //I belive its done in the ParentMapper
            public virtual int ParentId { get; set; } //ForeignKey  

            public virtual ICollection<Friend>   Friends        { get; set; }

            //The plan is to fetch all friends from the repository by using the ParentId and 
            //keep the entity as clean as possible.
            public virtual ICollection<Friend>   FamilyFriends  { get; set; }
        }
        public class Parent {
            public int IdParent { get; set; }
            public string ParentName {get;set;}

            public virtual ICollection<Friend>   Friends        { get; set; }
            public virtual ICollection<Child>    Children        { get; set; }
        }
    }


    {
        class ParentMapper : EntityTypeConfiguration<Parent>
        {
            public ParentMapper()
            {
                HasKey(one => one.IdParent);

                //I started out like this but its not possible....
                //But this will give an error obviusly
                HasMany(c => c.Children).WithRequired(d => d.ParentId).HasForeignKey(one => one.ParentId);
            }
        }
    }

    {
        class ChildMapper : EntityTypeConfiguration<Child>
        {
            public ChildMapper()
            {
                HasKey(one => one.IdChild);
            }
        }
    }
4

1 回答 1

1
public class Child {

        public int ChildId { get; set; }

        public string ChildName {get;set;}

        [ForeignKey("Parent")]
        public int ParentId { get; set; } //ForeignKey  
        public Parent Parent{get; set;}


        public List<Friend>   Friends        { get; set; }

        public List<Friend>   FamilyFriends  { get; set; }
    }
    public class Parent {
        public int ParentId { get; set; }
        public string ParentName {get;set;}

        public List<Friend>   Friends        { get; set; }
        public List<Child>    Children        { get; set; }
    }

    public class Friend
    {
        public int FriendId { get; set; }
        public string FriendName {get;set;}

        [ForeignKey("Parent")]
        public int ParentId{get;set;}
        public Friend Parent {get;set;}

        [ForeignKey("Child")]
        public int ChildId{get;set;}

        [InverseProperty("Friends")]
        public Child Child {get;set;}

         [ForeignKey("ChildFam")]
        public int ChildFamId{get;set;}

        [InverseProperty("FamilyFriends")]
        public Child ChildFam {get;set;}
    }
于 2013-06-04T09:18:55.363 回答