zoukankan      html  css  js  c++  java
  • Entity Framework Core

    Entity Framework 使用一组约定基于实体类的形状构建模型。 可指定其他配置以补充和/或替代约定的内容。

    本文介绍可应用于面向任何数据存储的模型的配置,以及面向任意关系数据库时可应用的配置。 提供程序还可支持特定于具体数据存储的配置。

    1、使用 fluent API 配置模型

    可在派生上下文中替代 OnModelCreating 方法,并使用 ModelBuilder API 来配置模型。 此配置方法最为有效,并可在不修改实体类的情况下指定配置。 Fluent API 配置具有最高优先级,并将替代约定和数据注释。

    using Microsoft.EntityFrameworkCore;
    
    namespace EFModeling.FluentAPI.Required
    {
        class MyContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
    
            #region Required
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Blog>()
                    .Property(b => b.Url)
                    .IsRequired();
            }
            #endregion
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
        }
    }

      分组配置

      为了减小 OnModelCreating 方法的大小,可以将实体类型的所有配置提取到实现 IEntityTypeConfiguration<TEntity> 的单独类中。

    public class BlogEntityTypeConfiguration : IEntityTypeConfiguration<Blog>
    {
        public void Configure(EntityTypeBuilder<Blog> builder)
        {
            builder
                .Property(b => b.Url)
                .IsRequired();
        }
    }

      然后,只需从 OnModelCreating 调用 Configure 方法:

    new BlogEntityTypeConfiguration().Configure(modelBuilder.Entity<Blog>());

      可以在给定程序集中应用实现 IEntityTypeConfiguration 的类型中指定的所有配置:

    modelBuilder.ApplyConfigurationsFromAssembly(typeof(BlogEntityTypeConfiguration).Assembly);

    2、使用数据注释来配置模型

      也可将特性(称为数据注释)应用于类和属性。 数据注释会替代约定,但会被 Fluent API 配置替代:

    using Microsoft.EntityFrameworkCore;
    using System.ComponentModel.DataAnnotations;
    
    namespace EFModeling.DataAnnotations.Required
    {
        class MyContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
        }
    
        #region Required
        public class Blog
        {
            public int BlogId { get; set; }
            [Required]
            public string Url { get; set; }
        }
        #endregion
    }
  • 相关阅读:
    Building a Space Station POJ
    Networking POJ
    POJ 1251 Jungle Roads
    CodeForces
    CodeForces
    kuangbin专题 专题一 简单搜索 POJ 1426 Find The Multiple
    The Preliminary Contest for ICPC Asia Shenyang 2019 F. Honk's pool
    The Preliminary Contest for ICPC Asia Shenyang 2019 H. Texas hold'em Poker
    The Preliminary Contest for ICPC Asia Xuzhou 2019 E. XKC's basketball team
    robotparser (File Formats) – Python 中文开发手册
  • 原文地址:https://www.cnblogs.com/hiwuchong/p/14141161.html
Copyright © 2011-2022 走看看