实体框架使用Code First多个多对多关系

时间:2015-04-23 10:11:59

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

我有两个班级Foo和Bar

public class Foo
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public virtual int Id { get; set; }


        private ICollection<Bar> _bar;
        public virtual ICollection<Bar> Bars
        {
            get { return _bar?? (_bar= new Collection<Bar>()); }
            set { _bar= value; }
        }
    }

酒吧

 public class Bar
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public virtual int Id { get; set; }


            private ICollection<Foo> _foo1;
            public virtual ICollection<Foo> Foos1
            {
                get { return _foo1?? (_foo1= new Collection<Foo>()); }
                set { _foo1= value; }
            }

               private ICollection<Foo> _foo2;
                public virtual ICollection<Foo> Foos2
                {
                    get { return _foo2?? (_foo2= new Collection<Foo>()); }
                    set { _foo2= value; }
                }


            }

然后我使用Migration来更新数据库。但是,而不是通常的表FooBar。 EF创建了2个表

Foo
Id,Bar_Id

Bar
Id,Foo_Id,Foo_Id1

这不是我想要的。我想通过在Bar中添加2个Foo系列搞砸了。我现在应该怎么做?

1 个答案:

答案 0 :(得分:1)

想出来,我需要做两件事来解决这个问题。首先,添加另一个Bar to Foo的集合

 public class Foo
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public virtual int Id { get; set; }


            private ICollection<Bar> _bar;
            public virtual ICollection<Bar> Bars
            {
                get { return _bar?? (_bar= new Collection<Bar>()); }
                set { _bar= value; }
            }

            private ICollection<Bar> _bar2;
            public virtual ICollection<Bar> Bars2
            {
                get { return _bar2?? (_bar2= new Collection<Bar>()); }
                set { _bar2= value; }
            }
        }

其次,使用InverseProperty明确告诉EF我想要2个多对多关系。

 public class Bar
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public virtual int Id { get; set; }


            private ICollection<Foo> _foo1;
            [InverseProperty("Bars")]
            public virtual ICollection<Foo> Foos1
            {
                get { return _foo1?? (_foo1= new Collection<Foo>()); }
                set { _foo1= value; }
            }

               private ICollection<Foo> _foo2;
                [InverseProperty("Bars2")]
                public virtual ICollection<Foo> Foos2
                {
                    get { return _foo2?? (_foo2= new Collection<Foo>()); }
                    set { _foo2= value; }
                }


            }

我现在最终得到4桌Foo,Bar,FooBarss和FooBar1