微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

EF Core 中必需与可选关系一对零或一的最佳方法是什么?

如何解决EF Core 中必需与可选关系一对零或一的最佳方法是什么?

我已经将 EntityFramework 6 的项目实现到 EntityFramework Core 中。我必须将 EF6 关系模式迁移到 EF 核心。 我在下面找到了一些参考资料:

  1. Entity Framework Core zero-or-one to zero-or-one relation

但没有得到任何关于 EF-Core 中的必需-可选关系的想法。

Sample1.cs:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .Hasrequired(x => x.Student)
                .WithOptional(x => x.StudentAddress);
}

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }
    public string State { get; set; }
    public virtual Student Student { get; set; }
}

Sample2.cs:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .HasKey(sa => sa.StudentId);
    modelBuilder.Entity<StudentAddress>()
                .Hasrequired(x => x.Student)
                .WithOptional(x => x.StudentAddress);
}

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }
    public string State { get; set; }
    public virtual Student Student { get; set; }
}

请有人帮助我如何使用 fluent api 在 EF-Core 中做到这一点

解决方法

你可以试试这个(参考:docs):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentAddress>()
                .HasOne(x => x.Student)
                .WithOne(x => x.StudentAddress).IsRequired(false);
}

或者,您可以在您的 StudentAddressId 模型中添加 FK Student 并使类型可以为空 int?

public class Student
{
    public int StudentId { get; set; }
    
    // This is the FK for StudentAddress.
    // Make it int? (nullable) if StudentAddress is optional
    public int? StudentAddressId { get; set; }
    public virtual StudentAddress StudentAddress { get; set; }
}

public class StudentAddress
{
    public int StudentId { get; set; }

    public virtual Student Student { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Since the FK is nullable,you don't need the IsRequired(false)
    modelBuilder.Entity<StudentAddress>()
                .HasOne(x => x.Student)
                .WithOne(x => x.StudentAddress);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。