2016-12-21 50 views
0

我有兩個實體,展望和人,我試圖做的是使用Prospect.ID作爲ProspectTable的主鍵和PersonID的外鍵,我的ideia使用兩個實體的相同ID,而不需要我的Prospect實體上的PersonID。當前景被保存在數據庫中時,它會嘗試保存一個PersonID,即使我沒有在我的Prospect實體上有這個屬性,我想知道ef核心是否支持這種關係。EF核心:同時使用ID作爲主鍵和外鍵

下面是我在模型構建器上得到的結果。

modelBuilder.Entity<ProspectDto>(builder => { builder.ToTable("Prospects"); builder.HasKey(prospect => prospect.ID); }); 

modelBuilder.Entity<PersonDto>(builder => { builder.HasOne(p => p.Prospect).WithOne().HasForeignKey<ProspectDto>(pe => pe.ID); }); 

這裏是正在對數據庫執行什麼:

INSERT INTO [Prospects] ([ID], [PersonID]) VALUES (@p421, @p422)

PersonDTO:

public class PersonDto : DtoBase 
{ 
    public PersonDto() 
    { 

    } 

    public ProspectDto Prospect { get; set; } 
} 

ProspectDTO:

public class ProspectDto : DtoBase 
{ 
    public ProspectDto() 
    { 

    } 

    public PersonDto Person { get; set; } = new PersonDto(); 
} 

DtoBase:

public abstract class DtoBase 
{ 
    public Guid ID { get; protected set; } 
} 

謝謝。

+0

請顯示'ProspectDto'和'PersonDto'類聲明(您可以跳過數據字段,與問題無關)。 – Dmitry

+0

@Dmitry更新 –

+0

嗯,看不到任何'ID'字段...猜猜它可能存在於'DtoBase'中...您能否提供關於您的模型的所有信息,與問題有關? – Dmitry

回答

1

只使用屬性,沒有FluentAPI:

public abstract class DtoBase 
{ 
    [Key] 
    public Guid ID { get; protected set; } 
} 

public class PersonDto : DtoBase 
{ 
    [InverseProperty("Person")] 
    public ProspectDto Prospect { get; set; } 
} 

public class ProspectDto : DtoBase 
{ 
    [ForeignKey("ID")]   // "magic" is here 
    public PersonDto Person { get; set; } = new PersonDto(); 
} 

我不知道什麼是等價的FluentAPI ForeignKey。所有其他(Key和InverseProperty)都是可配置的,但爲什麼使用兩種方法而不是一種。上述

代碼生成以下遷移代碼:

protected override void Up(MigrationBuilder migrationBuilder) 
{ 
    migrationBuilder.CreateTable(
     name: "Persons", 
     columns: table => new 
     { 
      ID = table.Column<Guid>(nullable: false) 
     }, 
     constraints: table => 
     { 
      table.PrimaryKey("PK_Persons", x => x.ID); 
     }); 

    migrationBuilder.CreateTable(
     name: "Prospects", 
     columns: table => new 
     { 
      ID = table.Column<Guid>(nullable: false) 
     }, 
     constraints: table => 
     { 
      table.PrimaryKey("PK_Prospects", x => x.ID); 
      table.ForeignKey(
       name: "FK_Prospects_Persons_ID", 
       column: x => x.ID, 
       principalTable: "Persons", 
       principalColumn: "ID", 
       onDelete: ReferentialAction.Cascade); 
     }); 
} 

看起來非常接近,你需要什麼。

+0

它完美的作品,謝謝。其他問題,你知道這相當於使用流利的API嗎? –

-1

如果您將關係建模爲一個:EF將自動將主體的PK用作FK作爲依賴項。

ModelBuilder.Entity<ProspectDto>().HasRequired(p => p.Person).WithRequiredDependent(); 

請注意,ProspectDto仍然會對DB(從DtoBase繼承)的ID列,但FK關係將是ProspectDto.IDPersonDto.ID之間應該沒有ProspectDto.PersonId列。

+0

HasRequired()在ef核心上不可用。 –

+0

對不起,應該仔細閱讀你的問題,這段代碼來自EF 6.1項目。 –