【问题标题】:Entity Framework 6 code first fluent API one to one relation with both ends requiredEntity Framework 6 code first fluent API 需要两端的一对一关系
【发布时间】:2018-11-05 02:59:45
【问题描述】:

我想首先在 Entity Framework 6 代码中使用 fluent API 实现两端所需的一对一关系。

我有主课:

public class Student
{
    public int Id{ get;  set;} 
    public string Name{ get;  set;}
    public StudentProfile StudentProfile { get; set; } 
}

我有依赖类:

public class StudentProfile
{
    public int Id{ get;  set;} 
    public string Description{ get;  set;}
    public Student Student { get; set; } 
}

另外,我有一对一关系的配置,在这种情况下,两端都是必需的:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
            .HasRequired(student => student.StudentProfile)
            .WithRequiredPrincipal(profile => profile.Student);

     base.OnModelCreating(modelBuilder);   
}

执行update-database后,生成的表是:

表 StudentProfile 列:

表格学生列:

在主程序中,我可以保存学生及其个人资料:

 UMLModel umlContext = new UMLModel();

 //Studentprofile object
 StudentProfile studentProfile = new StudentProfile();
 studentProfile.Description = "Emily Profile Description";

 //Student object
 Student student = new Student();
 student.Name = "Emily";
 student.StudentProfile = studentProfile;

 //Save Student and StudenProfile Objects
 umlContext.Students.Add(student);
 umlContext.SaveChanges();

执行主程序后,在数据库中,StudentProfiles 表为:

学生表是:

当我尝试在没有其个人资料的情况下保存一名学生时,问题就出现了,程序允许保存它但它应该不允许它:

UMLModel umlContext = new UMLModel();

Student student = new Student();
student.Name = "John";

umlContext.Students.Add(student);  
umlContext.SaveChanges();

执行主程序后,在数据库上,表 StudentProfiles 现在是:

对于学生表:

防止这种情况的一种方法是使用数据注释,但我不喜欢这种方法,因为域类需要额外的代码:

public class Student
{
    public int Id{ get;  set;} 
    public string Name{ get;  set;}
    [Required]
    public virtual StudentProfile StudentProfile { get; set; } 
}

问题:

  1. 这是来自 fluent API 的错误吗?
  2. 有什么方法可以在不修改的情况下使用 Fluent API 解决这个问题 域类?

提前致谢!

【问题讨论】:

  • 不回答问题,但从设计的角度来看,需要两端的一对一关系没有意义。只需创建 1 个包含学生和学生个人资料中的所有属性的类。

标签: entity-framework-6 relationship one-to-one ef-fluent-api


【解决方案1】:

也许可以在这里查看 Stack Overflow 的答案,它很好地解释了实体框架中的 1:1 映射以及如何映射它们的一些选项,因此两端都是必需的:https://stackoverflow.com/a/30516623/2128831

【讨论】:

    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2016-06-01
    • 1970-01-01
    • 2013-01-26
    相关资源
    最近更新 更多