一个用户可以有 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里面解释了。来自链接。
首先,您需要使用HasOne
和WithOne
。
其次,您必须使用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/