【问题标题】:Code First and Parent-Child referencesCode First 和父子引用
【发布时间】:2011-02-16 22:25:42
【问题描述】:

我正在使用 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'”。那么 - 这张照片有什么问题?

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

【问题讨论】:

    标签: code-first entity-framework-ctp5


    【解决方案1】:

    在 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);                
    }
    

    有关更多信息,请查看这篇文章:
    Associations in EF Code First CTP5: Part 2 – Shared Primary Key Associations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 2013-02-03
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多