映射不能首先对EF代码中的一个实体起作用

本文关键字:一个 起作用 实体 不能 代码 EF 映射 | 更新日期: 2023-09-27 18:12:53

我首先使用EF 6.1.1代码与.NET framework 4,我有一个抽象基类BaseEntity,所有其他我的实体继承自。我有以下类在我的模型:

public abstract class BaseEntity 
{
    public int Id { get; set; }
    ....
}
public class Document:BaseEntity
public class OrderHeader:Document
public class RequestHeader:Document

我想通过定义以下映射文件来改变EF默认的约定映射:

public class RequestHeader_Mapping : EntityTypeConfiguration<RequestHeader>
{
    public RequestHeader_Mapping()
    {                   
        this.ToTable("RequestHeader");
        this.Property(t => t.Id).HasColumnName("DocumentId");
        ...
    }
}
public class OrderHeader_Mapping : EntityTypeConfiguration<OrderHeader>
{
    public OrderHeader_Mapping()
    {                   
        this.ToTable("OrderHeader");
        this.Property(t => t.Id).HasColumnName("DocumentId");
        ...
    }
}
(更新)

public partial class Document_Mapping : BaseEntity_Mapping<Document>
{
    public Document_Mapping()
    {                   
        this.ToTable("Document");
        this.Property(t => t.Id).HasColumnName("Id");
        this.HasOptional(t => t.Creater).WithMany().HasForeignKey(d => d.CreatedById);
        this.HasOptional(t => t.Modifier).WithMany().HasForeignKey(d => d.ModifiedById);
        this.HasOptional(t => t.Owner).WithMany().HasForeignKey(d => d.OwnerId);
        this.HasOptional(t => t.DocumentStatu).WithMany().HasForeignKey(d => d.DocumentStatusId);
        this.HasOptional(t => t.DocumentStation).WithMany(t => t.Documents).HasForeignKey(d => d.DocumentStationId);
        this.HasOptional(t => t.DocumentType).WithMany().HasForeignKey(d => d.DocumentTypeId);
        this.HasOptional(t => t.DocumentFolder).WithMany().HasForeignKey(d => d.MainFolderId);
        this.HasOptional(t => t.SecurityLevel).WithMany).HasForeignKey(d => d.SecurityLevelId);
        this.Ignore(t => t.ToDocuments);
    }
}

public partial class BaseEntity_Mapping<TEntity> : EntityTypeConfiguration<TEntity> where TEntity:BaseEntity
{
    public BaseEntity_Mapping()
    {
        this.HasKey(e => e.Id);
         this.Property(t=>t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Ignore(t => t.MustDelete);
        this.Ignore(t=>t.PreviousState);
        this.Ignore(t => t.State);
    }
}

并在我的DbContext中以以下方式使用它们:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
     modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
     modelBuilder.Configurations.Add(new RequestHeader_Mapping());
     modelBuilder.Configurations.Add(new OrderHeader_Mapping());
     modelBuilder.Configurations.Add(new Document_Mapping());
 }

它适用于RequestHeader,但不适用OrderHeader,我的意思是RequestHeader表的生成键是DocumentId,但对于OrderHeaderId,我真的很困惑,知道有人在哪里有问题吗?

映射不能首先对EF代码中的一个实体起作用

我的OrderHeader与另一个实体有一个一对零或一个关系,当我删除它时,问题解决了!

相关文章: