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?
Replace
WithRequired
in yourOnModelCreating
method byWithOptionalPrincipal
:(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:
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.