Fluent Api 实体框架核心 [英] Fluent Api Entity Framework core

查看:30
本文介绍了Fluent Api 实体框架核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个用户可以拥有 1 个或 0 个帐户

A user can have 1 or 0 account

public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public Account Account { get; set; }
    }

    public class Account
    {
        public int AccountId { get; set; }         
        public DateTime CreatedDateTime { get; set; }
        public User User { get; set; }

    }

这是使用 Entity Framework 6 的 fluent api 代码

This is the fluent api code using Entity Framework 6

public class ClassDbContext: DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<User>()
                  .HasOptional(s => s.Account) 
                  .WithRequired(ad => ad.User);
    }
    public DbSet<User> Users { get; set; }
    public DbSet<Account> Accounts { get; set; }
}

这是结果 ResultImage

使用 Entity Framework Core 的等效 fluent api 代码是什么?

what is the equivalent fluent api code using Entity Framework Core?

推荐答案

@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 了解更多详情.

The child/dependent side could not be determined for the one-to-one relationship that was detected between 'Account.User' and 'User.Account'. To identify the child/dependent side of the relationship, configure the foreign key property. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.

它基本上在文档中进行了说明 来自链接.

It's basically explained in the documentation from the link.

首先,您需要使用HasOneWithOne.

First, you need to use HasOne and WithOne.

其次,您必须使用HasForeignKey来指定两个实体中的哪一个是依赖(当存在依赖时无法自动检测)实体之一中未定义单独的 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,即使用所谓的共享主键关联时)是否需要 FK 因为 PK 显然不能为 null).

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 Core fluent 配置如下:

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);
    });

这篇关于Fluent Api 实体框架核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆