且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EF代码首先对现有的数据库,映射一对多

更新时间:2023-01-12 13:39:40

您需要的是实体分裂 - 分裂两个或多个表之间的一个实体。这隐含包括共享主键 - 在此情况下,在关系表的共享密钥将是儿童实体的标识。您可以通过调用多个地图方法做到这一点,每一个调用 EntityMappingConfiguration.Properties 来定义哪些属性应包括在映射片段和 ToTable通话来设置表名。

What you need is entity splitting - splitting a single entity among two or more tables. This implicitly involves shared primary key - in this case, the shared key in the relationship table will be the child entities' ID. You do this by calling multiple Map methods, each with a call to EntityMappingConfiguration.Properties to define which properties should be included in that mapping fragment and a call to ToTable to set the table name.

modelBuilder.Entity<Measurement>()
    .HasKey( ke => ke.MeasurementId )
    .Map( emc =>
    {
        emc.Properties( pe => new { pe.MeasurementId, pe.Name, pe.DeviceId } );
        emc.ToTable( "Measurement" );
    } )
    .Map( emc =>
    {
        emc.Properties( pe => new { pe.MeasurementId, pe.ParentId } );
        // maybe name this MeasurementExtension?  This table could
        //  be used for any properties you wish to add to the Measurement entity
        emc.ToTable( "Measurement_Parent" );

        // for this example's clarity I've named the PK Child_MeasurementId
        //  but in real-world use I would name it MeasurementId
        emc.Property( pe => pe.MeasurementId ).HasColumnName( "Child_MeasurementId" );
        emc.Property( pe => pe.ParentId ).HasColumnName( "Parent_MeasurementId" );
    } );

modelBuilder.Entity<Measurement>()
    .HasOptional( npe => npe.Parent )
    .WithMany( npe => npe.Children )
    .HasForeignKey( fke => fke.ParentId );

下面是结果在DB(注意我并没有建立一个FK /导航道具为设备,但你知道如何做到这一点):

Here's the result in the DB (note I did not set up a FK/nav prop for Device but you know how to do that):

EF代码首先对现有的数据库,映射一对多

理想情况下, Parent_MeasurementId 字段会不为空和记录会被删除,而不是设置该栏为空,如果他们没有父母,但是这似乎并不可能与实体的分裂。在任何情况下,这样做你正在寻找什么 - 无需修改最初的基础表扩展实体

Ideally, the Parent_MeasurementId field would be not null and the record would be deleted instead of setting that column to null if their is no parent, but that doesn't seem possible with entity splitting. In any case, this does exactly what you're looking for - extending an entity without modifying the initial underlying table.