使用Entity Framework时,ASP.NET MVC中的Fluent API含义

时间:2015-03-15 10:09:52

标签: entity-framework

我正在学习ASP.NET MVC。并且为了创建PK和FK,我在.cs文件中的模型中添加了一些代码,如下所示

 public class Courses
    {
        public int CourseID { get; set; }
        [Key]
        public string CourseName { get; set; }
        public string Description { get; set; }
        public int Duration { get; set; }

        public virtual ICollection<Instructors> Instructors { get; set; }
    }

    public class Instructors 
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string CourseName { get; set; }
        [ForeignKey("CourseName")]
        public virtual Courses Courses { get; set; }
    }

我的问题是Fluent API的重要性是什么。我已经使用模型中的上述代码成功创建了PK和FK。那么什么是Fluent API以及为什么需要它?

1 个答案:

答案 0 :(得分:0)

实体框架Fluent Api是使用Entity framework Code First方法定义数据库模式的另一种方法。您在问题中使用的语法使用数据注释,这是另一种常用方法。

FluentApi的主要优点是您不必实际访问模型类以装饰它们。例如,当您将模型放在单独的装配中时,使用注释装饰它们根本不可能。另一方面,通过使用EF FluentAPI,您可以轻松地执行以下操作:

modelBuilder.Entity<Courses>().HasKey(c => c.CourseID);

在底线,两种方法都生成完全相同的数据库模式。 因此,如果您更喜欢使用数据注释并且您的项目结构允许它,您可以毫无疑问地使用它。在那些无法使用数据注释方法并且仍然希望使用Code First方法的情况下,FluentApi是正确的方法。