Entity Framework 一对一关系在依赖实体为空时不会抛出异常

Entity Framework 1-to-1 relationship does not throw an exception when dependent entity is null

我正在尝试在 Entity Framework 中进行一对一映射,我发现了一个示例 online was here, look for the 'Configure One-to-One relationship using Fluent API section'

大多数在线示例与 link 以及我在尝试实现它时阅读的一些书中的示例有些相似。

这是我的实体:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}

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

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

我的数据上下文,包括使用 fluent api:

的配置
public class DataContext : DbContext
{
    public DbSet<Student> Student { get; set; }

    // public DbSet<StudentAddress> Addresses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Configure StudentId as PK for StudentAddress
        modelBuilder.Entity<StudentAddress>()
            .HasKey(e => e.StudentId);

        // Configure StudentId as FK for StudentAddress
        modelBuilder.Entity<Student>()
                    .HasRequired(s => s.Address)
                    .WithRequiredPrincipal(ad => ad.Student);
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var context = new DataContext())
        {
            var student = new Student { StudentName = "sample name" };
            context.Student.Add(student);
            context.SaveChanges();
        }
        Console.ReadKey();
    }
}

在控制台应用程序中,我希望它抛出异常,因为 Student 必须有一个 StudentAddress 才能保存它,但是当我 运行 应用程序并检查时学生条目实际保存的数据库。我可能在幕后遗漏了一些东西,但如果我尝试在 Student class 的 StudentAddress 属性 之上添加 [Required] 属性,它会抛出如果我不为 Student 实体提供 StudentAddress,则会出现异常。

尝试删除关系主要端的声明。根据我的经验,仅当您使用 annotation/attributes 创建一对一关系时才需要这样做:

modelBuilder.Entity<Student>()
    .HasRequired(s => s.Address);

在一对一关系中,一端必须是主体,第二端必须是从属。 Principal 端是最先插入的端,它可以在没有从属端的情况下存在。从属端是必须插入主体之后的一端,因为它有主体的外键。

所以尝试删除这个:

.WithRequiredPrincipal(ad => ad.Student);

为了

.WithRequiredDependent(ad => ad.Student);

或者您可以删除该行或在 属性 ...

上使用 [Required] 数据注释

我向 EF 团队提交了一个错误,这里解释了为什么会这样。

https://github.com/aspnet/EntityFramework6/issues/66#issuecomment-248073084

来自 Arthur Vickers(EF 开发团队成员):

EF will always let you insert a new principal (Student in your model) without any dependents regardless of whether the relationship is required or not. A required relationship means that a dependent (Address in your model) cannot be inserted without a corresponding principal. I realize that the way relationships are modeled in EF6 implies something different, but the decision to describe relationships in this way and then behave like this was made many years ago and we cannot change it now.