如何在我的孩子中设置依赖于外键

时间:2013-06-04 07:34:46

标签: c# entity-framework ef-code-first

我需要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);
            }
        }
    }

1 个答案:

答案 0 :(得分: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;}
    }