【问题标题】:Advantage of defining relationships in Code First Fluent API?在 Code First Fluent API 中定义关系的优势?
【发布时间】:2014-05-05 12:51:48
【问题描述】:

我刚开始使用 EF Code First。我有一个关于这个的问题。通过 Fluent API 定义关系有什么优势?

当我从我的 poco(或实体)创建数据库时,我的表之间已经有了一对多和/或多对多的关系。

例如:

    public class School
    {
        public School()
        {
            Students = new List<Student>();
        }

        public Guid Id { get; set; }
        public string Name { get; set; }
        public List<Student> Student{ get; set; }
    }


public class Student
    {
        public Guid Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public Guid SchoolId{ get; set; }
        public School School{ get; set; }
    }

这已经在学生和学校之间建立了关系。通过 Fluent API 定义关系是否有优势?还是不行?

提前致谢!

【问题讨论】:

    标签: c# entity-framework ef-code-first


    【解决方案1】:

    使用 Fluent API 的最大优势是当您需要自定义某些内容时。在您的示例中,您在学校和学生之间建立了一对多的关系。您的导航属性准确地描述了这种关系,因为您在 School 类上有一个 List 并且在 Student 上有一个 School 属性。

    Fluent API 真正有用的地方在于,如果您出于某种原因想要保持这种关系,但出于某种原因不希望学校的学生使用导航属性:

    public class School
    {
        public School()
        {
            Students = new List<Student>();
        }
    
        public Guid Id { get; set; }
        public string Name { get; set; }
        // remove List<Student>
    }
    

    您仍然可以使用 Fluent API 来描述这种关系:

    modelBuilder.Entity<Student>()
        .HasRequired(req => req.School)
        .WithMany() // no navigation property
        .HasForeignKey(fk => fk.SchoolId);
    

    在您不想在模型本身中映射外键的情况下,它也很有用。如果您希望能够覆盖 Entity Framework 的某些约定,有时 Fluent API 是实现此目的的唯一方法。

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 2013-03-02
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 2012-01-20
      • 1970-01-01
      相关资源
      最近更新 更多