2

我正在使用 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' 中插入标识列的显式值”。

行。Strike 1 to Code First 因为没有识别出 Id 是一个标识列。我们可以解决这个问题,所以我们告诉 CodeFirst testa.id 是一个身份:

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

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

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

4

1 回答 1

3

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

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

有关更多信息,请查看这篇文章:
EF Code First CTP5 中的关联:第 2 部分 – 共享主键关联

于 2011-02-17T03:22:09.777 回答