简体   繁体   English

Identity 3.0 - 如何在分层应用程序中使用 AspNetUsers ID 作为外键

[英]Identity 3.0 - How to use AspNetUsers ID as Foreign Key in a Tiered Application

Intention:意图:

A Subscriptions database table which contains a UserId column, which has a foreign key relationship to the Id column of the AspNetUsers table.包含UserId列的Subscriptions数据库表,该列与AspNetUsers表的Id列具有外键关系。

Project Setup (in order of their reference hierarchy) :项目设置(按其参考层次结构的顺序)

  • Web Layer (Contains ApplicationDbContext and ApplicationUser class) Web层(包含ApplicationDbContext和ApplicationUser类)
  • DTO Layer DTO 层
  • Data Access Layer (Contains EFDbContext)数据访问层(包含 EFDbContext)

Project is Code-First configuration.项目是代码优先配置。

Database Setup:数据库设置:

Both ApplicationDbContext and EFDbContext reference the same database . ApplicationDbContext 和 EFDbContext 都引用同一个数据库

  • ApplicationDbContext: References all Identity entities ApplicationDbContext:引用所有 Identity 实体
  • EFDbContext: References my Subscriptions entity (among others) EFDbContext:引用我的订阅实体(等等)

Question:问题:

Given that my EFDbContext is located in my data layer, which does not contain any references to Identity 3.0 , is it possible to create a Foreign Key constraint between AspNetUsers and Subscriptions?鉴于我的 EFDbContext 位于我的数据层中,其中不包含对 Identity 3.0 的任何引用,是否可以在 AspNetUsers 和 Subscriptions 之间创建外键约束?

Is it possible to create a Foreign Key constraint between AspNetUsers and Subscriptions?是否可以在 AspNetUsers 和 Subscriptions 之间创建外键约束?

Sure it is.是的。 It's a common thing you will run into when you're crossing boundaries like that.当您像这样跨越边界时,您会遇到这种情况。

Instead of having EF create the relationships you need to而不是让 EF 创建您需要的关系

  • create a new empty migration创建一个新的空迁移
  • add the code to define the foreign key to the up method在 up 方法中添加定义外键的代码
  • add the code to undo the foreign key in the down method在down方法中添加撤消外键的代码
  • run the migration on the database在数据库上运行迁移

The migration will look something like:迁移将类似于:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddForeignKey(
            name: "FK_Table_PrincipalTable_TableId",
            table: "Table",
            column: "PrincipalTableId",
            principalTable: "PrincipalTable",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade)
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_Table_PrincipalTable_TableId",
            table: "Table");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM