Code First和Parent-Child引用

时间:2011-02-16 22:25:43

标签: code-first entity-framework-ctp5

我正在使用Code First CTP 5.我在父表和子表之间进行了相当简单的设置

Create table testA (
    id int not null identity(1,1),
    stuff varchar(200),
    primary key (id)
    );
go

create table testB (
    id int not null
        foreign key references testA(id),
    morestuff varchar(200),
    primary key (id)
    );
go

要使用Code First引用这些表,我们有以下结构:

namespace Test.Models
{
    public class TestEntities : DbContext
    {
        public DbSet<testa> testa { get; set; }
        public DbSet<testb> testb { get; set; }

        protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<testa>().ToTable("testa");
            modelBuilder.Entity<testa>()
                .Property(p => p.id)
                .HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);

            modelBuilder.Entity<testb>().ToTable("testb");
        }
    }


    public class testa
    {
        public int id { get; set; }
        public String stuff { get; set; }

        public virtual testb testb { get; set; }
    }

    public class testb
    {
        public int id { get; set; }
        public string morestuff { get; set; }

        public virtual testa testa { get; set; }
    }
}

当我尝试向testa添加记录时,我收到错误“当IDENTITY_INSERT设置为OFF时,无法在表'testA'中为标识列插入显式值。”

确定。为了不识别Id是标识列,将1打到Code First。我们可以解决这个问题,所以我们告诉CodeFirst testa.id是一个标识:

    modelBuilder.Entity<testa>()
        .Property(p => p.id)
        .HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);

我们再次运行它并得到另一个错误:“ReferentialConstraint中的依赖属性映射到存储生成的列。列:'id'”。那么 - 这张照片怎么了?

我做错了什么,如何解决?

1 个答案:

答案 0 :(得分:3)

在1:1关联中,Code First将其中一个实体识别为主体,将另一个实体识别为依赖实体。然后它将主PK作为标识,并且在插入从属表时需要处理有效的唯一PK。在您的情况下,它选择testb作为主体,但看起来您希望testa成为此关联的主要结尾。这可以通过使用流畅的API来实现,并且基本上给Code First提供关于哪一个是主体以及哪一个是依赖的提示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<testb>()
                .HasRequired(b => b.testa)
                .WithOptional(a => a.testb);                
}

有关详细信息,请查看以下文章:
Associations in EF Code First CTP5: Part 2 – Shared Primary Key Associations