用户可以拥有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<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代码是什么?
答案 0 :(得分:5)
@Tseng很接近,但还不够。使用建议的配置,您将获得带有消息的异常:
无法确定在“Account.User”和“User.Account”之间检测到的一对一关系的子/从属方。要标识关系的子/依赖方,请配置外键属性。有关详细信息,请参阅http://go.microsoft.com/fwlink/?LinkId=724062。
基本上在链接的documentation中进行了解释。
首先,您需要使用HasOne
和WithOne
。
其次,你必须使用HasForeignKey
来指定两个实体中的哪一个是依赖(当没有单独的FK时,它无法自动检测到其中一个实体中定义的属性。)
第三,没有所需的依赖。当依赖实体使用单独的FK(而不是您的情况下的PK,即所谓的共享主键关联IsRequired方法可用于指定是否需要FK >因为PK显然不能为空)。
话虽如此,发布模型的正确F Core流畅配置如下:
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);
});
答案 1 :(得分:1)
与其他名字几乎一样。
modelBuilder.Entity<User>()
.HasOne(s => s.Account)
.WithOne(ad => ad.User)
.IsRequired(false);