且构网

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

流利的Api实体框架核心

更新时间:2021-08-06 21:27:46

@Tseng很近,但还不够。借助建议的配置,您将获得以下消息的异常:

@Tseng is close, but not enough. With the proposed configuration you'll get exception with message:


无法一对一确定子方/从属方在 Account.User和 User.Account之间检测到的关系。要标识关系的子级/从属端,请配置外键属性。请参阅 http://go.microsoft.com/fwlink/?LinkId=724062 更多详细信息。

文档来自链接。

首先,您需要使用 HasOne WithOne

First, you need to use HasOne and WithOne.

第二,您必须使用 HasForeignKey 指定两个实体中的哪个是 dependent (当在其中一个实体中没有定义单独的FK属性时,不会自动检测到它)。

Second, you must use HasForeignKey to specify which one of the two entities is the dependent (it cannot be detected automatically when there is no separate FK property defined in one of the entities).

第三,没有更多所需的依存关系 IsRequired 方法可用于指定当从属实体使用单独的FK(而不是如您所愿的PK,即所谓的 Shared Primary Key Association ,因为PK显然不能为空)。

Third, there is no more required dependent. The IsRequired method can be used to specify if the FK is required or not when the dependent entity uses separate FK (rather than PK as in your case, i.e. with the so called Shared Primary Key Association because PK apparently cannot be null).

话虽如此,发布模型的正确F核心流利配置为

With that being said, the correct F Core fluent configuration of the posted model is as follows:

modelBuilder.Entity<User>()
    .HasOne(e => e.Account)
    .WithOne(e => e.User)
    .HasForeignKey<Account>(e => e.AccountId);

,结果是:

migrationBuilder.CreateTable(
    name: "User",
    columns: table => new
    {
        UserId = table.Column<int>(nullable: false)
            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
        Email = table.Column<string>(nullable: true),
        Name = table.Column<string>(nullable: true)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_User", x => x.UserId);
    });

migrationBuilder.CreateTable(
    name: "Account",
    columns: table => new
    {
        AccountId = table.Column<int>(nullable: false),
        CreatedDateTime = table.Column<DateTime>(nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Account", x => x.AccountId);
        table.ForeignKey(
            name: "FK_Account_User_AccountId",
            column: x => x.AccountId,
            principalTable: "User",
            principalColumn: "UserId",
            onDelete: ReferentialAction.Cascade);
    });