我使用EF4.3.1代碼首先,我有如下的代碼,操作失敗,因爲名爲'IX_ID'的索引或統計信息已經存在於'TestAs'表上?
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
using (var context = new myContext())
{
TestA ta = new TestA();
ta.Name = "Hero";
TestB tb = new TestB();
tb.Name = "Allen";
TestC tc = new TestC();
tc.Name = "Iverson";
ta.tb = tb;
ta.tc = tc;
context.testASet.Add(ta);
}
}
}
class TestA
{
public int ID { get; set; }
public string Name { get; set; }
public TestB tb { get; set; }
public TestC tc { get; set; }
}
class TestB
{
public int ID { get; set; }
public string Name { get; set; }
public TestA ta { get; set; }
}
class TestC
{
public int ID { get; set; }
public string Name { get; set; }
public TestA ta { get; set; }
}
class myContext : DbContext
{
public DbSet<TestA> testASet { get; set; }
public DbSet<TestB> testBSet { get; set; }
public DbSet<TestC> testCSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TestB>().HasOptional(x => x.ta).WithRequired();
modelBuilder.Entity<TestC>().HasOptional(x => x.ta).WithRequired();
modelBuilder.Entity<TestA>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<TestB>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<TestC>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
當我調試項目,拋出異常,「操作失敗,因爲索引或名稱爲「統計IX_ID '已經存在於'TestAs'表上。「 但是,如果我從代碼中,只有「種皮」和「TESTB」刪除「TESTC」,修改爲下面的代碼,
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
using (var context = new myContext())
{
TestA ta = new TestA();
ta.Name = "Hero";
TestB tb = new TestB();
tb.Name = "Allen";
ta.tb = tb;
context.testASet.Add(ta);
}
}
}
class TestA
{
public int ID { get; set; }
public string Name { get; set; }
public TestB tb { get; set; }
}
class TestB
{
public int ID { get; set; }
public string Name { get; set; }
public TestA ta { get; set; }
}
class myContext : DbContext
{
public DbSet<TestA> testASet { get; set; }
public DbSet<TestB> testBSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TestB>().HasOptional(x => x.ta).WithRequired();
modelBuilder.Entity<TestA>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<TestB>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
一切正常。有人知道爲什麼拋出異常嗎?
我以爲我們[解決了這個](http://stackoverflow.com/questions/9564158/ef4-3-create-one-to-one-or-zero-relationship-failed)?再次,您有'HasOptional(...)。WithRequired()'兩次。 – 2012-03-12 10:03:27