c# - Fluent Api Entity Framework 核心

标签 c# entity-framework entity-framework-core ef-fluent-api

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

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 代码

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 的等效流式 API 代码是什么?

最佳答案

@Tseng 很接近,但还不够。使用建议的配置,您将收到异常消息:

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.

基本在documentation里面解释了。来自链接。

首先,您需要使用HasOneWithOne

其次,您必须使用HasForeignKey 指定两个实体中的哪一个是依赖(当有没有在其中一个实体中定义单独的 FK 属性)。

第三,不再有必需的依赖IsRequired 方法可用于指定当依赖实体使用单独的 FK 时是否需要 FK(而不是您的情况下的 PK,即所谓的共享主键关联 因为 PK 显然不能为空)。

话虽如此,贴出的模型正确的F Core fluent配置如下:

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

关于c# - Fluent Api Entity Framework 核心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43546825/

相关文章:

c# - float 错误计算

c# - 在 Dictionary<> 子类中重命名 Key 和 Value 属性的最简单方法是什么

sql-server - 将 MAXDOP 添加到 Linq to Entities

c# - 尝试保存实体时 ModelState.isvalid 为 false,错误表示相关实体中需要一个字段

c# - 对于路由代码中指定的 Controller /方法来说,使用 "specifications"是不是很糟糕?

c# - 自动 .ToString()?

c# - 更新到 EF 7.0.0-rc1-final 破坏了 SQL DbContextOptionsBuilder UseSqlServer

c# - 如何在 Entity Framework Core 2.0 中的模型本身内部使用 OnModelCreating?

mysql - 无法使用 Entity Framework 连接到Mysql主/从

sqlite - 无法加载文件或程序集 SQLitePCLRaw.core