EF4.3 create one to one or zero relationship faile

2019-09-02 01:45发布

I use EF4.3 to create 1 to 1...0 relationship, but it throw an exception of

"The operation failed because an index or statistics with name 'IX_id' already exists on table 'TestAs'"

The code as below

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (myContext context = new myContext())
            {
                TestA tA = new TestA();
                TestB tB = new TestB();
                TestC tC = new TestC();
                context.testA.Add(tA);
                context.testB.Add(tB);
                context.testC.Add(tC);
                context.SaveChanges();
            }
        }
    }

    class TestA
    {
        public int id { get; set; }
        //public TestB NavB { get; set; }
        //public TestC NavC { get; set; }
    }

    class TestB
    {
        public int id { get; set; }
        public TestA NavA { get; set; }
    }

    class TestC
    {
        public int id { get; set; }
        public TestA NavA { get; set; }
    }

    class myContext : DbContext
    {
        public DbSet<TestA> testA { get; set; }
        public DbSet<TestB> testB { get; set; }
        public DbSet<TestC> testC { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithRequired();
            modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithRequired();
        }
    }
}

Anyone can help?

1条回答
【Aperson】
2楼-- · 2019-09-02 02:41

Replace WithRequired in your OnModelCreating method by WithOptionalPrincipal:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithOptionalPrincipal();
  modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithOptionalPrincipal();
}

(If A would be the principal entity you'd use WithOptionalDependent.)

EDIT

After your comments I think it would be interesting to see the effect of adding two classes TestD and TestE, giving A two navigation properties TestD and TestE and do this in your model:

modelBuilder.Entity<TestB>().HasOptional(x => x.NavA).WithOptionalPrincipal();
modelBuilder.Entity<TestC>().HasOptional(x => x.NavA).WithOptionalPrincipal();
modelBuilder.Entity<TestA>().HasRequired(x => x.NavD);
modelBuilder.Entity<TestA>().HasRequired(x => x.NavE);

Table A now has four foreign keys: to B and C (nullable), to D and E (not nullable). I think the latter is what you want.

查看更多
登录 后发表回答