Any Fluent API tutorials that use EF Database-First approach to explain the subject?

后端 未结 3 1857
逝去的感伤
逝去的感伤 2021-02-06 10:51

There are many tutorials on Fluent API, but they all explain it using Entity Framework Code-First code examples. Since I don\'t know Code-First, do you know of any Fluent API tu

3条回答
  •  醉梦人生
    2021-02-06 11:34

    There are no tutorials which would explain the Fluent API together with Database-First approach because Fluent API is made only for Code-First approach. You don't need the Fluent API if you want to create your model via Database-First.

    Fluent API (together with Code-First data annotations and conventions) is a tool to define model details in code, such as string length, if a property is required or the type of relationship - many-to-many, one-to-many, etc. When using Database-First or Model-First the EDMX file has the same purpose - it contains all the details and mapping definitions of your model. Fluent API (+ data annotations and conventions) replaces the EDMX file only when using Code-First.

    If you create the model via Database-First or Model-First, you will have an EDMX file representing your model. You can apply the T4 DbContext Generator to this EDMX file. The generated files have two characteristics being different from Code-First:

    • The generated connection string contains a section refering to the EDMX metadata which will be embedded into your assembly:

      connectionString="metadata=res://*/Model.csdl
                                |res://*/Model.ssdl
                                |res://*/Model.msl;
                        ..."
      
    • The generated context DbContext will have an overridden OnModelCreating method which just throws an exception:

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          throw new UnintentionalCodeFirstException();
      }
      

    As long as you leave the metadata section in the connection string, EF won't even call OnModelCreating or any code in Fluent API in this method. The metadata section tells EF that your model is DB- or Model-First and that the metadata are defined in the embedded EDMX and not in Fluent API.

    However, you can remove the metadata section from the connection string, remove the UnintentionalCodeFirstException and write code with Fluent API in OnModelCreating. You can follow this procedure to create an initial model via Database-First and then build on this initial model for further development with Code-First.

    At this point you are not working anymore with Database-First, but Code-First instead and everything you read about Fluent API is valid for you.

提交回复
热议问题