流利的Apientity framework核心

用户可以拥有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的流畅的api代码

 public class ClassDbContext: DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasOptional(s => s.Account) .WithRequired(ad => ad.User); } public DbSet Users { get; set; } public DbSet Accounts { get; set; } } 

这是ResultImage的结果

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

@Tseng很接近,但还不够。 使用建议的配置,您将获得带有消息的exception:

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

它基本上在链接的文档中进行了解释。

首先,您需要使用HasOneWithOne

其次, 必须使用HasForeignKey指定两个实体中的哪一个是从属实体(当其中一个实体中没有定义单独的FK属性时,无法自动检测到它)。

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

话虽如此,发布模型的正确F Core流畅配置如下:

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

结果是:

 migrationBuilder.CreateTable( name: "User", columns: table => new { UserId = table.Column(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Email = table.Column(nullable: true), Name = table.Column(nullable: true) }, constraints: table => { table.PrimaryKey("PK_User", x => x.UserId); }); migrationBuilder.CreateTable( name: "Account", columns: table => new { AccountId = table.Column(nullable: false), CreatedDateTime = table.Column(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); }); 

与其他名字几乎一样。

 modelBuilder.Entity() .HasOne(s => s.Account) .WithOne(ad => ad.User) .IsRequired(false);